Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Selecting the maximum count from a GROUP BY operation

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?

like image 603
atiyar Avatar asked Jan 08 '23 01:01

atiyar


2 Answers

If you want ties

SELECT top (1) with ties Name, COUNT(*) AS [count]
  FROM Person 
 GROUP BY Name  
 ORDER BY count(*) DESC
like image 109
paparazzo Avatar answered Jan 10 '23 21:01

paparazzo


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
like image 22
Mureinik Avatar answered Jan 10 '23 20:01

Mureinik