如何使用max函数缩小查询范围?

时间:2019-04-29 12:01:24

标签: mysql sql

Incorrect Query Result

我正在使用PHP MyAdmin。我希望此查询的结果是Willard Wildcats和7,但我不知道如何通过使用max函数而不是order by和limit函数来做到这一点。我需要使用max函数

Select Team_Name, Count(*)
From Number_3
Group By Team_Name

此查询的结果应为

Willard Wildcats and 7

2 个答案:

答案 0 :(得分:1)

使用LIMIT子句:

SELECT Team_Name, Count(*) AS CNT 
FROM Number_3
GROUP BY Team_Name
ORDER BY CNT DESC
LIMIT 1;

如果您受LIMIT子句的限制,请使用子查询:

SELECT Team_Name, Count(*) AS CNT 
FROM Number_3
GROUP BY Team_Name
HAVING Count(*) = (SELECT MAX(CNT)
                   FROM (SELECT Team_Name, Count(*) AS CNT 
                         FROM Number_3
                         GROUP BY Team_Name
                        ) t
                  );

如果您正在使用MySQL的最新版本,那么使用排名功能会更加容易:

SELECT t.*
FROM (SELECT Team_Name, Count(*) AS CNT,
             DENSE_RANK() OVER (ORDER BY Count(*) DESC) AS Seq 
      FROM Number_3
      GROUP BY Team_Name
     ) t
WHERE Seq = 1;

答案 1 :(得分:1)

您需要写出where条件并使用max函数选择一列

Select Team_Name, Count(*) From Number_3 where Team_Name=(select max(Count(*)) from Number_3)