从GROUP BY操作中选择最大计数

时间:2015-07-04 18:35:09

标签: sql select sql-server-2008-r2 group-by max

原谅我的SQL知识,但我有一个Person表,其中包含以下数据 -

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

我希望得到以下结果 -

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

如果我使用GROUP BY查询 -

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

它给了我 -

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

但我只想要最大数量的那个。我怎么做到的?

4 个答案:

答案 0 :(得分:3)

在SQL Server中执行此操作的最简单方法是使用top语法:

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

答案 1 :(得分:3)

如果你想要联系

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

答案 2 :(得分:1)

试试这个......

192

答案 3 :(得分:1)

答案是:

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)