问题
I'd like to transpose the results of a MySQL query from a per row key => value resultset to a resultset where the key is the column header and the value is a row entry for that column.
i.e. Given the following data
|------------------+-------------|
| CLASS_LESSON | ATTENDANTS |
|------------------+-------------|
| class1art | 1 |
| class1history | 1 |
| class2geography | 2 |
|------------------+-------------|
I'd like to transform it to
|------------+---------------+------------------|
| class1art | class1history | class2geography |
|------------+---------------+------------------|
| 1 | 1 | 2 |
|------------+---------------+------------------|
Assume that the class/lesson pairs are dynamic; they can be added or removed at any time. I don't want to explicitly call them out as suggested in the typical 'pivot table' sql solution.
select
MAX(CASE WHEN class_lesson = 'class1art' THEN attendants ELSE 0 END) AS class1art,
MAX(CASE WHEN class_lesson = 'class1history' THEN attendants ELSE 0 END) AS class1history,
MAX(CASE WHEN class_lesson = 'class2geography' THEN attendants ELSE 0 END) AS class2geography,
MAX(CASE WHEN class_lesson = 'class7art' THEN attendants ELSE 0 END) AS class7art,
MAX(CASE WHEN class_lesson = 'class7history' THEN attendants ELSE 0 END) AS class7history
from
(select
group_concat(distinct class, lesson) as class_lesson,
count(*) as attendants
from
TableName
group by class , lesson
) a
Here's an SQLFiddle environment with sample data. Is this possible without utilizing stored procedures?
回答1:
Try this
SELECT
MAX(CASE WHEN t.CLASS_LESSON = 'class1art' THEN t.ATTENDANTS ELSE NULL END) AS class1art,
MAX(CASE WHEN t.CLASS_LESSON = 'class1history' THEN t.ATTENDANTS ELSE NULL END) AS class1history,
MAX(CASE WHEN t.CLASS_LESSON = 'class2geography' THEN t.ATTENDANTS ELSE NULL END) AS class2geography
FROM
(
select
group_concat(distinct class, lesson) as class_lesson, count(*) as attendants
from
TableName
group by
class, lesson
) as t
FIDDLE DEMO
回答2:
Try this one, Why you want 1 for class2geography it should be 2.
SELECT
MAX(CASE WHEN t.clsubject = 'class1art' THEN t.attndee ELSE NULL END) AS class1art,
MAX(CASE WHEN t.clsubject = 'class1history' THEN t.attndee ELSE NULL END) AS class1history,
MAX(CASE WHEN t.clsubject = 'class2geography' THEN t.attndee ELSE NULL END) AS class2geography
FROM
(
SELECT CONCAT(class,lesson) AS clsubject, COUNT(*) AS attndee FROM TableName GROUP BY clsubject
) t
来源:https://stackoverflow.com/questions/21304446/transpose-the-results-of-a-mysql-query