Sqlserver
 sql >> Database >  >> RDS >> Sqlserver

Come aumentare il contatore in select

Con una funzione cte e window Row_Number()... Tuttavia, dovrei notare che sarebbe meglio sostituire (Select NULL) nella clausola OVER con una sequenza corretta (ad esempio identity int, datetime).

Declare @YourTable table (ColumnA int)
Insert Into @YourTable values (1),(0),(0),(0),(1),(0),(0),(0),(0),(1),(0),(1),(0),(0),(1),(0)

;with cte as (
    Select *,RN=Row_Number() over (Order By (Select Null)) from @YourTable
)
Select A.ColumnA
      ,ColumnB = sum(B.ColumnA)
 From  cte A
 Join  cte B on (B.RN<=A.RN)
 Group By A.ColumnA,A.RN
 Order By A.RN

Resi

ColumnA ColumnB
1       1
0       1
0       1
0       1
1       2
0       2
0       2
0       2
0       2
1       3
0       3    
1       4
0       4
0       4
1       5
0       5