Mysql组由生成一行

时间:2014-04-15 14:33:37

标签: mysql group-by grouping

我有这个查询

SELECT IF( sort_order =1, title, NULL ) AS q1, IF( sort_order =2, title, NULL ) AS q2,
       IF( sort_order =3, title, NULL ) AS q3
FROM  `choice` 
WHERE  `question_id` =1101

显示此结果

    q1    q2       q3
Pollster  NULL     NULL

NULL      Snooper  NULL

NULL      NULL     The Tank

有没有办法分组或订购会给我这个结果

    q1    q2       q3
Pollster  Snooper  The Tank

1 个答案:

答案 0 :(得分:1)

是。只需包含聚合函数:

SELECT max(IF( sort_order =1, title, NULL )) AS q1,
       max(IF( sort_order =2, title, NULL )) AS q2,
       max(IF( sort_order =3, title, NULL )) AS q3
FROM  `choice` 
WHERE  `question_id` = 1101;