按-SQL选择前3个最多计数组

时间:2014-05-07 19:22:44

标签: mysql sql sql-server oracle subquery

我下面有一个sql声明,根据国家/地区名称进行分组。

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

结果示例:

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

我想要前三个最大价值国家。在上面的例子中我只想要:

Country           Count
-------           -----
Saudi Arabia      28
America           20
Japan             14

4 个答案:

答案 0 :(得分:8)

取决于您使用的RDBMS:

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

<强> 甲骨文:

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;

答案 1 :(得分:4)

SELECT *
FROM   (SELECT   COUNTRY,count(*) 
        FROM     DRUG_SEIZURE 
        WHERE    COUNTRY IS NOT NULL 
        GROUP BY COUNTRY
        ORDER BY 2 DESC)
WHERE  rownum <= 3;

答案 2 :(得分:3)

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

答案 3 :(得分:0)

请参阅:

http://troels.arvin.dk/db/rdbms/#select-limit

可以很好地概述如何根据标准限制结果集,以及许多不同的DBMS。