mysql

group by 可以按列分组,分组后,除分组列和聚合函数作用列外,其他列默认取每组的第一行(并无实际意义)

例如:

1. 按stuid分组,查询结果中,name、subject、score均取的是每组第一行

 

2. 按stuid分组,按组求和,结果也是一样:除stuid和sum(score)两列外,其余name、subject均是取每组第一行 

 

 avg()同理

  

 3. 按stuid分组,求最大值,会发现:查询结果中最大值‘90’是第二行,但‘李四’‘语文’仍取的是第一行(无实际意义)

 

题目1:

-- 计算每个人的总成绩并排名(要求显示字段:姓名,总成绩)
select name, sum(score) as total from tb_3 group by stuid order by total desc

-- 计算每个人的总成绩并排名(要求显示字段: 学号,姓名,总成绩)
select stuid, name, sum(score) as total from tb_3 group by stuid order by total desc

-- 计算每个人的平均成绩(要求显示字段: 学号,姓名,平均成绩)
select stuid, name, avg(score) from tb_3 group by stuid

题目2:(注意:需要复合查询)

-- 计算每个人单科的最高成绩(要求显示字段: 学号,姓名,课程,最高成绩)  
select a.stuid, a.name, a.subject, b.maxscore from tb_3 a inner join (select stuid, name, max(score) as maxscore from tb_3 group by stuid) b
on a.stuid = b.stuid and a.score = b.maxscore

-- 列出各门课程成绩最好的学生(要求显示字段: 学号,姓名,科目,成绩) 
select a.stuid, a.name, a.subject, b.maxscore from tb_3 a inner join (select subject, max(score) as maxscore from tb_3 group by subject) b
on a.subject = b.subject and a.score = b.maxscore

题目3:

如下表,找出得分最高的学生及其分数

答案一(错误):

答案二(正确):

原文地址:https://www.cnblogs.com/xiaochongc/p/14721225.html