问题
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