create table t_score( id int primary key auto_increment, name varchar(20) not null, #名字 Subject varchar(10) not null, #科目 Fraction double default 0 #分数 );
-- 插入数据
INSERT INTO `t_score`(name,Subject,Fraction) VALUES ('王海', '语文', 86), ('王海', '数学', 83), ('王海', '英语', 93), ('陶俊', '语文', 88), ('陶俊', '数学', 84), ('陶俊', '英语', 94), ('刘可', '语文', 80), ('刘可', '数学', 86), ('刘可', '英语', 88), ('李春', '语文', 89), ('李春', '数学', 80), ('李春', '英语', 87);
方法一、if
select name as 名字 , sum(if(Subject='语文',Fraction,0)) as 语文, sum(if(Subject='数学',Fraction,0))as 数学, sum(if(Subject='英语',Fraction,0))as 英语, round(AVG(Fraction),2) as 平均分, SUM(Fraction) as 总分 from t_score group by name union select name as 名字 , sum(语文) Chinese,sum(数学) Math,sum(英语) English,round(AVG(总分),2)as 平均分,sum(总分) score from( select 'TOTAL' as name, sum(if(Subject='语文',Fraction,0)) as 语文, sum(if(Subject='数学',Fraction,0))as 数学, sum(if(Subject='英语',Fraction,0))as 英语, SUM(Fraction) as 总分 from t_score group by Subject )t
上面简单的语句更新了我以往的写sql的习惯
-- oracle语法
select name as 名字 , sum(case when subject='语文' then score else '0' end) 语文, sum(case when subject='数学' then score else '0' end) 数学, sum(case when subject='英语' then score else '0' end) 英语, round(AVG(score),2) as 平均分, sum(score)/count(*) , SUM(score) as 总分 from lagfunction group by name -- 2.0在oracle中自己常用的习惯 select name ,sum(A),sum(B),sum(C) ,(sum(A)+sum(B)+sum(C) )/count(*) from ( select NAME ,SCORE AS A,0 AS B,0 AS c from lagfunction WHERE subject='语文' union select NAME ,0 AS A,SCORE AS B,0 AS c from lagfunction WHERE subject='数学' union select NAME ,0 AS A,0 AS B,SCORE AS c from lagfunction WHERE subject='英语' )c GROUP BY NAME
发现自己以往写作习惯真是太基础了,
方法二、case
select name as Name, sum(case when Subject = '语文' then Fraction end) as Chinese, sum(case when Subject = '数学' then Fraction end) as Math, sum(case when Subject = '英语' then Fraction end) as English, sum(fraction)as score from t_score group by name UNION ALL select name as Name,sum(Chinese) as Chinese,sum(Math) as Math,sum(English) as English,sum(score) as score from( select 'TOTAL' as name, sum(case when Subject = '语文' then Fraction end) as Chinese, sum(case when Subject = '数学' then Fraction end) as Math, sum(case when Subject = '英语' then Fraction end) as English, sum(fraction)as score from t_score group by Subject)t
方法三、使用with rollup
select ifnull(name,'TOll') name, sum(if(Subject='语文',Fraction,0)) as 语文, sum(if(Subject='英语',Fraction,0)) as 英语, sum(if(Subject='数学',Fraction,0))as 数学, sum(Fraction) 总分 from t_score group by name with rollup
◆with rollup的作用是在最下面加上一行总的求和,看下图,当涉及到avg的时候,该函数智能的求了个总的平均,有意思!
参考:https://www.cnblogs.com/weibanggang/p/9679301.html