tSQL:每组增加 1

tSQL: Increase every group by 1

尊敬的论坛和 SQL 专家,

是否可以通过 SQL 将每个组变化增加 1? 我已经尝试过 Dense_Rank、Row_Number 等聚合函数......但没有成功。

示例:

这里可以找到一些测试数据

DECLARE   @test  TABLE ([Session]  int, Sort int)
Insert into @test Values (1,1)
Insert into @test Values (1,2)
Insert into @test Values (1,3)
Insert into @test Values (0,4)
Insert into @test Values (0,5)
Insert into @test Values (1,6)
Insert into @test Values (1,7)
Insert into @test Values (1,8)
Insert into @test Values (1,9)
Insert into @test Values (1,10)
Insert into @test Values (1,11)
Insert into @test Values (1,12)
Insert into @test Values (1,13)
Insert into @test Values (0,14)
Insert into @test Values (1,15)
Insert into @test Values (0,16)
Insert into @test Values (1,17)
Insert into @test Values (1,18)
Insert into @test Values (1,19)
Insert into @test Values (1,20)
select * from @test

使用 LAG()SUM() window 函数:

SELECT SUM(flag) OVER (ORDER BY Sort) GroupNumber, Session, Sort
FROM (
  SELECT *, CASE WHEN Session = LAG(Session) OVER (ORDER BY Sort) THEN 0 ELSE 1 END flag
  FROM @test
) t

参见demo