SELECT userid, SUM(CASE `subject` WHEN '语文' THEN score ELSE 0 END) as '语文', SUM(CASE `subject` WHEN '数学' THEN score ELSE 0 END) as '数学', SUM(CASE `subject` WHEN '英语' THEN score ELSE 0 END) as '英语', SUM(CASE `subject` WHEN '政治' THEN score ELSE 0 END) as '政治' FROM tb_score GROUP BY userid 2、使用IF() 进行行转列:
SELECT userid, SUM(IF(`subject`='语文',score,0)) as '语文', SUM(IF(`subject`='数学',score,0)) as '数学', SUM(IF(`subject`='英语',score,0)) as '英语', SUM(IF(`subject`='政治',score,0)) as '政治' FROM tb_score GROUP BY userid 注意点:
3、利用SUM(IF()) 生成列 + WITH ROLLUP 生成汇总行,并利用 IFNULL将汇总行标题显示为Total
SELECT IFNULL(userid,'total') AS userid, SUM(IF(`subject`='语文',score,0)) AS 语文, SUM(IF(`subject`='数学',score,0)) AS 数学, SUM(IF(`subject`='英语',score,0)) AS 英语, SUM(IF(`subject`='政治',score,0)) AS 政治, SUM(IF(`subject`='total',score,0)) AS total FROM( SELECT userid,IFNULL(`subject`,'total') AS `subject`,SUM(score) AS score FROM tb_score GROUP BY userid,`subject` WITH ROLLUP HAVING userid IS NOT NULL )AS A GROUP BY userid WITH ROLLUP;
4、利用SUM(IF()) 生成列 + UNION 生成汇总行,并利用 IFNULL将汇总行标题显示为 Total
SELECT userid, SUM(IF(`subject`='语文',score,0)) AS 语文, SUM(IF(`subject`='数学',score,0)) AS 数学, SUM(IF(`subject`='英语',score,0)) AS 英语, SUM(IF(`subject`='政治',score,0)) AS 政治, SUM(score) AS TOTAL FROM tb_score GROUP BY userid UNION SELECT 'TOTAL',SUM(IF(`subject`='语文',score,0)) AS 语文, SUM(IF(`subject`='数学',score,0)) AS 数学, SUM(IF(`subject`='英语',score,0)) AS 英语, SUM(IF(`subject`='政治',score,0)) AS 政治, SUM(score) FROM tb_score
5、利用SUM(IF()) 生成列,直接生成结果不再利用子查询
SELECT IFNULL(userid,'TOTAL') AS userid, SUM(IF(`subject`='语文',score,0)) AS 语文, SUM(IF(`subject`='数学',score,0)) AS 数学, SUM(IF(`subject`='英语',score,0)) AS 英语, SUM(IF(`subject`='政治',score,0)) AS 政治, SUM(score) AS TOTAL FROM tb_score GROUP BY userid WITH ROLLUP;
6、动态,适用于列不确定情况
SET @EE=''; select @EE :=CONCAT(@EE,'sum(if(subject= /'',subject,'/',score,0)) as ',subject, ',') AS aa FROM (SELECT DISTINCT subject FROM tb_score) A ; SET @QQ = CONCAT('select ifnull(userid,/'TOTAL/')as userid,',@EE,' sum(score) as TOTAL from tb_score group by userid WITH ROLLUP'); -- SELECT @QQ; PREPARE stmt FROM @QQ; EXECUTE stmt; DEALLOCATE PREPARE stmt;
7、合并字段显示:利用group_concat()
SELECT userid,GROUP_CONCAT(`subject`,":",score)AS 成绩 FROM tb_score GROUP BY userid