Tsql SQL在分组依据后重新编号索引
我有以下输入表:Tsql SQL在分组依据后重新编号索引,tsql,group-by,partitioning,rowset,Tsql,Group By,Partitioning,Rowset,我有以下输入表: Seq Group GroupSequence 1 0 2 4 A 3 4 B 4 4 C 5 0 6 6 A 7 6 B 8 0
Seq Group GroupSequence
1 0
2 4 A
3 4 B
4 4 C
5 0
6 6 A
7 6 B
8 0
输出表为:
Line NewSeq GroupSequence
1 1
2 2 A
3 2 B
4 2 C
5 3
6 4 A
7 4 B
8 5
输入表的规则如下:
Flg
,它将指示一个新的组序列(值为1或0)。然后,通过一个窗口函数求和(Flg)是一件小事
编辑-更新的Flg方法
示例
Declare @YourTable Table ([Seq] int,[Group] int,[GroupSequence] varchar(50))
Insert Into @YourTable Values
(1,0,null)
,(2,4,'A')
,(3,4,'B')
,(4,4,'C')
,(5,0,null)
,(6,6,'A')
,(7,6,'B')
,(8,0,null)
Select Line = Row_Number() over (Order by Seq)
,NewSeq = Sum(Flg) over (Order By Seq)
,GroupSequence
From (
Select *
,Flg = case when [Group] = lag([Group],1) over (Order by Seq) then 0 else 1 end
From @YourTable
) A
Order By Line
返回
Line NewSeq GroupSequence
1 1 NULL
2 2 A
3 2 B
4 2 C
5 3 NULL
6 4 A
7 4 B
8 5 NULL