Select up to x rows of each group

[亡魂溺海] 提交于 2019-12-12 02:23:43

问题


With a table of:

id | name       | job      | rank
01   john         teacher    4
02   mark         teacher    2
03   phil         plummer    1
04   dave         teacher    7
05   jim          plummer    9
06   bill         plummer    2

How can I select up to 2 rows of each job (if possible sorted by rank ASC in each group, so that the lowest two ranking of each group get picked). The result I'd be looking for is:

02 mark teacher 2
01 john teacher 4
03 phil plummer 1
06 bill plummer 2

This basically groups by job, with a limit to 2 and sorted by rank. I've been trying with GROUP BY as well as LEFT JOIN, but I just can't figure out how to do this. When creating a "temporary list" of jobs with GROUPING BY job, how do I join more than once onto that job?


回答1:


SELECT  id, name, job, rank
FROM    TableName a
WHERE 
        (
           SELECT   COUNT(*) 
           FROM     TableName as f
           WHERE    f.job = a.job AND 
                    f.rank <= a.rank
        ) <= 2;
  • SQLFiddle Demo


来源:https://stackoverflow.com/questions/15295489/select-up-to-x-rows-of-each-group

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