in MYSQL return 总分最高的学生姓名

in MYSQL return Student name with highest score overall

即一个叫 table 的学生(假设只有一个学生叫这个名字,例如,没有两个叫约翰·史密斯的学生) studentName, studentScore, 学科

假设 table 有这个

John Smith 40 maths
bob grey 20 english
anne hank 23 english
John Smith 30 english
anne grey 10 maths

我试图通过计算所有学生平均分的最大值来找到得分最高的学生

此处将 select 最高平均分但不是具有该平均分的学生姓名:

SELECT MAX(avgStudentScore)
FROM (SELECT AVG(studentScore) AS avgStudentScore FROM students GROUP BY studentName) t

感谢

如果你只需要名字,你可以这样做:

select studentName, avg(studentScore) as avgStudentScore
from students
group by studentName
order by avgStudentScore desc
limit 1

这将 return 仅查询的第一行。由于按 avgStudentScore 排序,它将 return 平均分最高的学生。


以上解决方案是最简单、最快的,但不是唯一的。如果你想做"the hard way"(带子查询),你需要做的是:

  1. 计算每个学生的平均值
  2. 获得最高平均值
  3. 筛选平均分最高的学生

所以...让我们用艰难的方式来做吧;)

select a.studentName
from 
    (
        select studentName, avg(studentScore) as avgStudentScore
        from students
        group by studentName
    ) as a
where 
    a.avgStudentScore = (
        select max(avgStudentScore) 
        from (
            select avg(studentScore) as avgStudentScore 
            from students 
            group by studentName
        ) as a
    )

请注意,使用这种方法,最终结果可能不是唯一的(即可能有一个或多个学生的平均分相同,而那个平均分是最高的)。

使用这个查询:

SELECT studentName, max( mark ) as maxMark FROM `student` GROUP BY studentName