在MySQL中选择多个值的MAX函数

问题描述 投票:0回答:1

我正在使用MYSQL来获得TA拥有的最大学生数量。通过此查询,我可以获得所有助教和每个助教的学生人数

SELECT TA.Name as Name, COUNT(Lecture.Student) AS studentcount 
FROM TA 
JOIN Lecture 
WHERE TA.TA_PUID = Lecture.TA 
GROUP BY TA.Name
ORDER BY studentcount DESC;

我的输出是这个

David    2 
Justin   2
Matt     2
Jennifer 1
Hannah   1
Timothy  1
Bob      1

我想只获得具有最大学生价值的助教。我该怎么做?在这种情况下,我希望输出为

David  2 
Justin 2
Matt   2
mysql sql jdbc
1个回答
0
投票

您可以使用rank()

SELECT t.*
FROM (SELECT TA.Name as Name, COUNT(*) AS studentcount,
             RANK() OVER (ORDER BY COUNT(*) DESC) as seqnum
      FROM TA JOIN
           Lecture l
           ON TA.TA_PUID = l.TA
      GROUP BY TA.Name
    ) t
WHERE seqnum = 1;

请注意,JOIN后面应带有ON子句,而不是WHERE子句。

© www.soinside.com 2019 - 2024. All rights reserved.