Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Select top 3 most count group by - SQL

I have an sql statement below which do group based on country names.

SELECT COUNTRY,count(*) FROM DRUG_SEIZURE WHERE COUNTRY IS NOT NULL GROUP BY COUNTRY

Result Sample:

Country           Count
-------           -----
America           20
Saudi Arabia      28
China             10
Japan             14
Kenya             10
Pakistan          12
India             11

I want the top three max value countries. In the above case i only want:

Country           Count
-------           -----
Saudi Arabia      28
America           20
Japan             14
like image 587
user3400389 Avatar asked May 07 '14 19:05

user3400389


3 Answers

Depending on what RDBMS you are using:

SQL SERVER:

SELECT TOP 3 COUNTRY, count(*) 
FROM DRUG_SEIZURE 
WHERE COUNTRY IS NOT NULL 
GROUP BY COUNTRY
ORDER BY count(*) DESC

MySQL:

SELECT COUNTRY, count(*) 
FROM DRUG_SEIZURE 
WHERE COUNTRY IS NOT NULL 
GROUP BY COUNTRY
ORDER BY count(*) DESC
LIMIT 3

Oracle:

SELECT *
FROM (
  SELECT COUNTRY, count(*) 
  FROM DRUG_SEIZURE 
  WHERE COUNTRY IS NOT NULL 
  GROUP BY COUNTRY
  ORDER BY count(*) DESC
) mr
WHERE rownum <= 3
ORDER BY rownum;
like image 79
Linger Avatar answered Oct 16 '22 18:10

Linger


SELECT *
FROM   (SELECT   COUNTRY,count(*) 
        FROM     DRUG_SEIZURE 
        WHERE    COUNTRY IS NOT NULL 
        GROUP BY COUNTRY
        ORDER BY 2 DESC)
WHERE  rownum <= 3;
like image 35
Mureinik Avatar answered Oct 16 '22 18:10

Mureinik


SELECT TOP 3 COUNTRY, COUNT(*) 
FROM DRUG_SEIZURE 
WHERE COUNTRY IS NOT NULL 
GROUP BY COUNTRY
ORDER BY COUNT(*) DESC
like image 3
Tom Avatar answered Oct 16 '22 19:10

Tom