开发者

SQL - Select 'n' greatest elements in group

开发者 https://www.devze.com 2023-04-07 11:00 出处:网络
The SQL MAX aggregate function will allow you to select the开发者_运维知识库 top element in a group. Is there a way to select the top n elements for each group?

The SQL MAX aggregate function will allow you to select the开发者_运维知识库 top element in a group. Is there a way to select the top n elements for each group?

For instance, if I had a table of users that held their division rank, and wanted the top two users per division ...

Users
userId | division | rank
1      | 1        | 1
2      | 1        | 2
3      | 1        | 3
4      | 2        | 3

I would want the query to somehow return users 2,3,4

If it matters, I'm using MySQL.


select * from users as t1
where (select count(*) from users as t2
       where t1.division = t2.division and t2.rank > t1.rank) <2
order by division,rank


Try this:

  SELECT *
    FROM (
         SELECT *, row_number() OVER (PARTITION BY division ORDER BY rank DESC) as rn
           FROM users
         ) as extended_users
   WHERE rn <= 2
ORDER BY userId


   SELECT * FROM (
      SELECT u1.userid, u1.rank 
      FROM users u1
      GROUP BY u1.division
      HAVING u1.rank = MAX(u1.rank)
      ORDER BY u1.rank DESC
    UNION
      SELECT u2.userid, u2.rank 
      FROM users u2
      WHERE u2.id <> u1.id
      GROUP BY u2.division
      HAVING u2.rank = MAX(u2.rank)
      ORDER BY u2.rank DESC
    ) ranking
    ORDER BY ranking.userid 


SELECT * from users u0
WHERE NOT EXISIS (
  SELECT * FROM users u1
  WHERE u1.division = u0.division
  AND u1.rank >= u0.rank +2
  );

BTW: most people count ranks starting from zero: poll-position gets rank=1, the second gets rank=2, et cetera. In that case you rank is 1+ the number of people before you in the ranking

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号