SQL Server:如何选择同一组的前2条记录?

时间:2013-12-13 11:09:13

标签: sql sql-server sql-server-2008

我正在使用SQL Server 2008.我有一个问题,我需要获取由2列CodePeriod确定的组中的前2条记录,然后将其插入另一列表

以下是一个示例表:

Code  |  Period  |  Dept  | DeptWorkPartSum
001      2013-11    D1      53
001      2013-11    D2      33
001      2013-11    D3      12
002      2013-11    D2      30
002      2013-11    D4      28
002      2013-11    D5      15
002      2013-12    D2      100

我想要摆脱的是:

Code  |  Period  |  Dept  | DeptWorkPartSum
001      2013-11    D1      53
001      2013-11    D2      33
002      2013-11    D2      30
002      2013-11    D4      28
002      2013-12    D2      100

这可能是一个非常简单的解决方案,但我现在无法弄明白。

3 个答案:

答案 0 :(得分:2)

一种简单的方法是使用具有CTE排名功能的ROW_NUMBER

WITH CTE AS
(
    SELECT Code,Period,Dept,DeptWorkPartSum,
           RN = ROW_NUMBER() OVER (PARTITION BY Code,Period, Dept
                                   ORDER BY DeptWorkPartSum)
    FROM dbo.TableName
)
SELECT Code,Period,Dept,DeptWorkPartSum
FROM CTE
WHERE RN <= 2

Demo

但是,您所需的结果似乎不正确,因为Dept对于所有三个代码都不同。

也许您不希望按Dept分组,但按顺序排序,结果是正确的:

WITH CTE AS
(
    SELECT Code,Period,Dept,DeptWorkPartSum,
           RN = ROW_NUMBER() OVER (PARTITION BY Code,Period
                                   ORDER BY Dept, DeptWorkPartSum)
    FROM dbo.TableName
)
SELECT Code,Period,Dept,DeptWorkPartSum
FROM CTE
WHERE RN <= 2

Demo

答案 1 :(得分:0)

SELECT Code, Period, Dept, DeptWorkPartSum
FROM (
  SELECT Code, Period, Dept, DeptWorkPartSum
    ,ROW_NUMBER ( ) OVER ( PARTITION BY Code, Period, Dept ORDER BY DeptWorkPartSum DESC) r
  FROM table) q
WHERE r <= 2

答案 2 :(得分:0)

try this:


with cte as
(
select *,ROW_NUMBER() over (partition by Code,Period,Dept order by Code) as rn from table
)

select Code,Period,Dept,DeptWorkPartSum from cte where rn<=2 

fiddle demo