SQL - Select 'n' greatest elements in 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
精彩评论