How to select top x records for every group

穿精又带淫゛_ 提交于 2019-12-10 22:53:43

问题


I tried something like this

select Id,UserId from myTable group by Id,UserId having COUNT(UserId)<7

Now what i want to do is selecting 6 records for each userid. But my approach failed.

So what is the correct syntax ?

Id is primary key clustered index


回答1:


This should get you pretty close

WITH    r ( userid, rnk )
      AS ( SELECT   userid, RANK() OVER ( PARTITION BY id ) AS rnk
           FROM     MyTable 
           GROUP BY userid)
SELECT  r.*
FROM    r
WHERE   r.Rank <= 6 


来源:https://stackoverflow.com/questions/14025255/how-to-select-top-x-records-for-every-group

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