问题
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