Selecting the maximum count from a GROUP BY operation

自作多情 提交于 2021-02-04 18:50:11

问题


Forgive my SQL knowledge, but I have a Person table with following data -

Id          Name
----        ------
1           a
2           b
3           b
4           c

and I want the following result -

Name      Total
------    ------
b         2

If I use the GROUP BY query -

SELECT Name, Total=COUNT(*) FROM Person GROUP BY Name  

It gives me -

Name   Total
------ ------
a      1
b      2
c      1

But I want only the one with maximum count. How do I get that?


回答1:


If you want ties

SELECT top (1) with ties Name, COUNT(*) AS [count]
  FROM Person 
 GROUP BY Name  
 ORDER BY count(*) DESC



回答2:


The easiest way to do this in SQL Server would be to use the top syntax:

SELECT   TOP 1 Name, COUNT(*) AS Total 
FROM     Person 
GROUP BY Name  
ORDER BY 2 DESC



回答3:


The answer is:

WITH MaxGroup AS (
   SELECT Name, COUNT(*) AS Total
   FROM Person
   GROUP BY Name)
SELECT Name, Total
FROM MaxGroup
WHERE Total = (SELECT MAX(Total) FROM MaxGroup)



回答4:


try this...

SELECT Name, COUNT(*) 
        FROM Person 
        GROUP BY Name 
        having COUNT(*)=( SELECT max(COUNT(*)) FROM Person GROUP BY Name) ;


来源:https://stackoverflow.com/questions/31223977/selecting-the-maximum-count-from-a-group-by-operation

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!