SQL仅显示每个actionid的前2条注释

时间:2011-06-25 21:01:35

标签: sql sql-server

  

可能重复:
  Selecting the top n rows within a group by clause

我有以下数据:

id actionid commentid 
1  1        1 
2  1        2
3  1        3
4  2        1 

我想创建一个sql,只显示每个actionid的前2条评论。在这种情况下,我应该只返回id(1,2,4)

由于

1 个答案:

答案 0 :(得分:1)

SELECT id, 
       actionid, 
       commentid
FROM (
   SELECT id, 
          actionid, 
          commentid, 
          row_number() over (partition by actionid order by id) rn
   FROM your_table
) t
WHERE rn <= 2