简单例子 数据结构如下
use dataTest create table t_score ( name varchar(24) , subject varchar(24), grade double(5,2) ) INSERT INTO `t_score` VALUES ('王海', '语文', 86), ('王海', '数学', 83), ('王海', '英语', 93), ('陶俊', '语文', 88), ('陶俊', '数学', 84), ('陶俊', '英语', 94), ('刘可', '语文', 80), ('刘可', '数学', 86), ('刘可', '英语', 88), ('李春', '语文', 89), ('李春', '数学', 80), ('李春', '英语', 87); select name, sum(case when subject = '语文' then grade end) as Chiese, sum(case when subject = '数学' then grade end) as Math, sum(case when subject = '英语' then grade end) as English, sum(grade) as score from t_score group by name union select 'TOTAL', sum(case when subject = '语文' then grade end) as Chiese, sum(case when subject = '数学' then grade end) as Math, sum(case when subject = '英语' then grade end) as English, sum(grade) as score from t_score #第二种方式 select name as Name, sum(IF(subject = '语文',grade,0))Chiese, sum(IF(subject = '数学',grade,0))Math, sum(IF(subject = '英语',grade,0))English, sum(grade)score from t_score GROUP BY name UNION ALL select 'TOTAL', sum(IF(subject = '语文',grade,0))Chiese, sum(IF(subject = '数学',grade,0))Math, sum(IF(subject = '英语',grade,0))English, sum(grade)score from t_score -- 第三种 select ifnull(name,'TOTAL')name, sum(IF(subject = '语文',grade,0))Chiese, sum(IF(subject = '数学',grade,0))Math, sum(IF(subject = '英语',grade,0))English, sum(grade)score from t_score GROUP BY name with rollup
结果