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           
输入表的规则如下:

  • “组”列中的任何正整数都表示行被分组在一起。整个字段可以为NULL或空白。null或0表示该行是独立处理的。在上面的示例中,有两个组和三个“单”行

  • GroupSequence列是在组内排序的单个字符。NULL、空白、“A”、“B”、“C”、“D”是唯一允许的字符

  • 若组有正整数,则GroupSequence中必须有字母字符

  • 我需要一个查询,该查询使用一个新列创建输出表,该列按如下所示顺序排列。 外部应用程序需要以行或NewSeq顺序(相同顺序,不同值)遍历此表

    我尝试了groupby、partitionby、OVER()等的变体,但没有成功。 非常感谢您的帮助。

    也许这会有所帮助

    这里唯一的技巧是
    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