简体   繁体   中英

MAX Function to select multiple values in MYSQL

I am using MYSQL to get the maximum number of students a TA has. 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() :

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.

You don't mention the version of MySQL. In MySQL 8.x you can use a CTE (Common Table Expression) to pre-compute the values. 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:

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM