表结构如下:
name schedule score
'张三' '语文' '20'
'张三' '数学' '60'
'张三' '英语' '80'
'李四' '数学' '30'
'李四' '英语' '60'
'李四' '语文' '80'
想要的结果如下:
姓名 语文 数学 英语 总成绩
'张三', '20', '60', '80', '160'
'李四', '80', '30', '60', '170'
需要的sql 语句如下:
select t.name,
sum((case when t.schedule ='语文' then t.score ELSE 0 END)) AS 语文,
sum((case when t.schedule ='数学' then t.score ELSE 0 END)) AS 数学,
sum((case when t.schedule ='英语' then t.score ELSE 0 END)) AS 英语,
sum(t.score) as 总成绩
from account t
group by t.name;
另外想要获取 每门课的最高成绩的学生信息sql语句的写法:
select b.* from (select max(score) score,`subject` from classes group by subject) a,classes b
where a.score = b.score and a.subject = b.subject ;