【问题标题】:Limit SQL query to only the top two counts per group [duplicate]将 SQL 查询限制为每组的前两个计数 [重复]
【发布时间】:2013-06-25 15:52:51
【问题描述】:

如果我有一个名为 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

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

【问题讨论】:

  • CA Vanilla 应该是 2,我猜。
  • @Glenn 在表格中添加了一行来解决这个问题

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


【解决方案1】:
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

【讨论】:

  • 我收到ORA-00923: FROM keyword not found where expected
  • 抱歉,我的错误,删除了 rownumber 上的 '' 并且应该可以正常工作。这是一个小提琴:SQLFiddle
猜你喜欢
  • 2014-03-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-07-07
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多