根据位字段将数据分区为子组

时间:2010-12-10 00:25:12

标签: sql-server sql-server-2008

我有前4列数据,我不想使用SQL 2008 R2中的Ranking函数来派生第五列。基于nextiteminsubgroup和previousiteminsubgroup字段将数据划分为子组的最佳方法是什么?

 Group  OrderInGroup    NextItemInSubGroup  PreviousItemInSubGroup  SubGroup
    1   1   1   0   1
    1   2   1   1   1
    1   3   1   1   1
    1   4   0   1   1
    1   5   0   0   2
    1   6   0   0   3
    1   7   1   0   4
    1   8   1   1   4
    1   9   0   1   4
    2   1   0   0   1
    2   2   0   0   2
    2   3   0   0   3
    2   4   1   0   4
    2   5   0   1   4
    3   1   0   0   1
    4   1   0   0   1
    4   2   0   0   2
    4   3   0   0   3

2 个答案:

答案 0 :(得分:0)

似乎0和0重新开始排名。

Select
      Rank() Over ( 
        Partition By 
          [Group]
        , Case When [NextItemInSubGroup] + [PreviousItemInSubGroup] = 0
               Then 0
               Else 1
          End
        Order By [OrderInGroup]
      ) as [SubGroup]
From Your_Table;

答案 1 :(得分:0)

递归CTE解决方案:

DECLARE @t TABLE
([Group]  INT 
,OrderInGroup  INT
,NextItemInSubGroup INT
,PreviousItemInSubGroup INT
,SubGroup INT
)

INSERT @t
VALUES
(1,1,1,0,1),(1,2,1,1,1),(1,3,1,1,1),(1,4,0,1,1),(1,5,0,0,2),(1,6,0,0,3),
(1,7,1,0,4),(1,8,1,1,4),(1,9,0,1,4),(2,1,0,0,1),(2,2,0,0,2),(2,3,0,0,3),
(2,4,1,0,4),(2,5,0,1,4),(3,1,0,0,1),(4,1,0,0,1),(4,2,0,0,2),(4,3,0,0,3)

;WITH recCTE
AS
(
    SELECT  [Group], OrderInGroup,NextItemInSubGroup , PreviousItemInSubGroup, 1 AS subgroup
    FROM @t
    WHERE OrderInGroup = 1

    UNION ALL

    SELECT  r.[Group], t.OrderInGroup,t.NextItemInSubGroup , t.PreviousItemInSubGroup, 
            CASE WHEN r.NextItemInSubGroup = 1 THEN r.subgroup ELSE r.subgroup + 1 END
    FROM recCTE AS r
    JOIN @t AS t
    ON t.[Group] = r.[Group]
    AND t.OrderInGroup = r.OrderInGroup + 1
)   
SELECT * FROM recCTE
ORDER BY [Group],OrderInGroup ;

P.S。最好避免使用SQL关键字(例如GROUP)作为表/列名称