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 SELECT * FROM ( SELECT u1.userid, u1