如何在SQL Server中选择每个id组的前2位

时间:2011-10-07 15:28:14

标签: sql sql-server

我有以下查询并针对每个id 即时通讯获得超过3个动作/代码 你能告诉我如何获得前两名 通过使用select语句而不是对每个id的操作 写一个程序

SELECT     id, 
           code,
           date,
           des
FROM         accounts INNER JOIN
                      accdesc ON accoints.code = accdesc.act_cd
ORDER BY accounts.id

查询返回以下数据

id  code    date        desc 

609 AG1     2005-11-07  a                    
609 AG2     2004-11-12  a clear                 
609 AG2     2002-04-28  a clear                 
609 AG2     1998-07-20  a clear                 
609 AG2     1998-03-16  a clear                 
627 AG9     2010-02-24  a9
627 AONOSP  2010-02-19  possession  
627 AONSPV  2010-02-24  visit            
627 SP AG1  2007-11-01  agreement                  
627 AONSPV  2010-02-22  visit            

我想要每个id的前2名

id  code    date        desc 
609 AG1     2007-11-07  a                    
609 AG2     2002-11-12  a clear               

627 AONOSP  2010-02-19  a9  
627 AONSPV  2010-02-24  poessession           

1 个答案:

答案 0 :(得分:10)

在SQL 2005及更高版本中,您可以ROW_NUMBER使用partition而不是您感兴趣的分组(id)来为该组中的每一行编号,然后您可以滚动到CTE或Derived表中,然后使用外部查询进行过滤:

SELECT 
  x.id, x.code, x.date, x.des
FROM
(
  SELECT 
    ROW_NUMBER() OVER (PARTITION BY Id ORDER BY accounts.id) as rownum,
    id, code, date, des
  FROM accounts
    INNER JOIN accdesc 
    ON accounts.code = accdesc.act_cd 
) x -- Derived Table
WHERE 
   rownum <= 2; -- How many rows of each group

请注意,您需要对排序采取意见(ORDER BY是强制性的)