Limit SQL query to only the top two counts per group [duplicate]

可紊 提交于 2019-12-10 19:32:34

问题


If I have a DB table called FAVORITE_FLAVOR where each row has a user's favorite flavor of ice cream.

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

Now, if I want to query the 2 most popular flavors in each state (normalizing capitalization and whitespace), I could query:

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;

Which returns:

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

Now, I only wanted to know the top 2 flavors per state. How do I limit the query so that Rocky Road is no longer listed.


回答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


来源:https://stackoverflow.com/questions/17355130/limit-sql-query-to-only-the-top-two-counts-per-group

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!