【问题标题】:MAX Function to select multiple values in MYSQLMYSQL中选择多个值的MAX函数
【发布时间】:2020-03-17 17:59:46
【问题描述】:

我正在使用 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

我只想获得学生人数最多的 TA。我怎样才能做到这一点?在这种情况下,我希望我的输出是

David  2 
Justin 2
Matt   2

【问题讨论】:

    标签: mysql sql jdbc


    【解决方案1】:

    你可以使用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 子句。

    【讨论】:

      【解决方案2】:

      在 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
      );
      

      如果你使用 MySQL 8+,windowing functionscommon table expressions 绝对是首选。

      【讨论】:

        【解决方案3】:

        你没有提到 MySQL 的版本。在 MySQL 8.x 中,您可以使用 CTE(通用表表达式)来预先计算值。然后,过滤很容易。

        例如:

        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)
        

        【讨论】:

          猜你喜欢
          • 2020-07-04
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2011-04-14
          • 1970-01-01
          • 2015-01-10
          • 1970-01-01
          相关资源
          最近更新 更多