转置MySQL查询的结果

时间:2014-01-23 09:43:55

标签: mysql sql transpose

我想从每行键转换MySQL查询的结果=>将结果集值为结果集,其中键是列标题,值是该列的行条目。

即。鉴于以下数据

|------------------+-------------|
|  CLASS_LESSON    | ATTENDANTS  |
|------------------+-------------|
|  class1art       | 1           |
|  class1history   | 1           |
|  class2geography | 2           |
|------------------+-------------|

我想将其转换为

|------------+---------------+------------------|
|  class1art | class1history | class2geography  |
|------------+---------------+------------------|
|  1         | 1             | 2                |
|------------+---------------+------------------|

假设课程/课程对是动态的;它们可以随时添加或删除。我不想按照typical 'pivot table' sql解决方案中的建议明确地将它们调出来。

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

这是一个包含示例数据的SQLFiddle环境。 这可能不使用存储过程吗?

2 个答案:

答案 0 :(得分:0)

试试这个

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

答案 1 :(得分:0)

试试这个,为什么你想要1为class2geography它应该是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