[英]MAX Function to select multiple values in MYSQL
I am using MYSQL to get the maximum number of students a TA has.我正在使用 MYSQL 来获取助教拥有的最大学生人数。 With this query I get all the TA's and the number of students of each 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;
My output is this我的输出是这个
David 2
Justin 2
Matt 2
Jennifer 1
Hannah 1
Timothy 1
Bob 1
I want to get only the TA's with the max value of students.我只想获得具有最大学生价值的助教。 How can I accomplish this?
我怎样才能做到这一点? In this case I want my output to be
在这种情况下,我希望我的输出是
David 2
Justin 2
Matt 2
You can use rank()
:您可以使用
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;
Note that JOIN
should be followed by an ON
clause rather than a WHERE
clause.请注意,
JOIN
后面应该跟一个ON
子句而不是WHERE
子句。
You don't mention the version of MySQL.你没有提到 MySQL 的版本。 In MySQL 8.x you can use a CTE (Common Table Expression) to pre-compute the values.
在 MySQL 8.x 中,您可以使用 CTE(公用表表达式)来预先计算值。 Then, filtering is easy.
然后,过滤很容易。
For example:例如:
with
a as (
SELECT TA.Name as Name, COUNT(Lecture.Student) AS studentcount
FROM TA
JOIN Lecture
WHERE TA.TA_PUID = Lecture.TA
GROUP BY TA.Name
)
select * from a where studentcount = (select max(studentcount) from a)
Prior to MySQL 8, you'll have to do something like this:在 MySQL 8 之前,您必须执行以下操作:
SELECT TA.Name as Name, COUNT(Lecture.Student) AS studentcount
FROM TA INNER JOIN Lecture ON TA.TA_PUID = Lecture.TA
GROUP BY TA.Name
HAVING studentCount = (
SELECT COUNT(Student) AS studentcount
FROM Lecture
GROUP BY TA
ORDER BY studentcount DESC
LIMIT 1
);
If you are using MySQL 8+, the windowing functions and common table expressions are definitely the first choice though.如果您使用的是 MySQL 8+,那么窗口函数和公用表表达式绝对是首选。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.