如何在mysql中实现这样的数据透视表?

时间:2013-09-13 09:44:39

标签: mysql pivot-table

我有以下查询显示学生的月费状况。

SELECT regd, Name_of_Student, Class, Section, Rollno,
If(Month = 'January', Status, 0) AS Jan,
If(Month = 'September', Status, 0) AS Sept  
FROM fee
where Class='XI(Art)' and Rollno='2';

此代码的问题如图所示:

enter image description here

我想输出的内容如下:

enter image description here

在实际应用中,我会显示所有月份。

请参阅小提琴here

1 个答案:

答案 0 :(得分:3)

SELECT regd, Name_of_Student, Class, Section, Rollno,
MAX(If(Month = 'January', Status, 0)) AS Jan,
MAX(If(Month = 'September', Status, 0)) AS Sept  
FROM fee
where Class='XI(Art)' and Rollno='2'
GROUP BY regd, Name_of_Student, Class, Section, Rollno;