Return first x results from each group in SQL query

此生再无相见时 提交于 2019-12-10 11:54:33

问题


I have a very complicated SQL query that returns a few hundred results broken down as follows:

    user 1    id: ##      stuff
    user 1    id: ##      stuff
    user 1    id: ##      stuff
     ....
    user 2    id: ###     stuff
    user 2    id: ###     stuff
    user 2    id: ###     stuff
    ....

for about 6 users. It's already sorted exactly the way I want, I just want the first 5 for each user. Is there an easy way to do this? I'm using PostgreSQL 8.4 btw, and my SQL knowledge is limited so try to make any explanations not too complicated if possible :D


回答1:


Something like this should do it.

SELECT t.user, t.id, t.stuff
    FROM (SELECT user, id, stuff,
                 ROW_NUMBER() OVER (PARTITION BY user ORDER BY id) AS RowNum
              FROM YourTable) t
    WHERE t.RowNum <= 5


来源:https://stackoverflow.com/questions/6390479/return-first-x-results-from-each-group-in-sql-query

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