将SQL查询限制为每组最多两个计数

时间:2013-06-27 23:54:40

标签: sql oracle oracle10g aggregate-functions greatest-n-per-group

如果我有一个名为FAVORITE_FLAVOR的数据库表,其中每一行都有用户最喜欢的冰淇淋味。

User ID | Flavor      | State
1       | Chocolate   | CA
2       | Vanilla     | ND
3       |   Chocolate | CA
4       | Rocky Road  | CA
5       | vanilla     | CA
6       | Vanilla     | CA
7       | Vanilla     | CA

现在,如果我想查询每个州最流行的2种口味(规范化大写和空格),我可以查询:

SELECT state, INITCAP(TRIM(flavor)), count(INITCAP(TRIM(flavor))) AS total
FROM favorite_flavor GROUP BY state, INITCAP(TRIM(flavor))
ORDER BY state ASC, total DESC;

返回:

CA | Vanilla    | 3
CA | Chocolate  | 2
CA | Rocky Road | 1
ND | Vanilla    | 1

现在,我只想知道每个州的前两种口味。如何限制查询以便不再列出Rocky Road。

1 个答案:

答案 0 :(得分:5)

SELECT
   State,
   flv,
   total
FROM (SELECT
         ROW_NUMBER() OVER ( PARTITION BY state ORDER BY count(INITCAP(TRIM(flavor))) DESC ) RowNumber,
         State,
         INITCAP(TRIM(flavor)) flv,
         count(INITCAP(TRIM(flavor))) total
      FROM favorite_flavor
      GROUP BY state, INITCAP(TRIM(flavor))
      ) dt
WHERE RowNumber <= 2
ORDER BY state ASC, total DESC