How to get cumulative sum

前端 未结 16 2610
遇见更好的自我
遇见更好的自我 2020-11-22 03:32
declare  @t table
    (
        id int,
        SomeNumt int
    )

insert into @t
select 1,10
union
select 2,12
union
select 3,3
union
select 4,15
union
select 5,23         


        
16条回答
  •  我在风中等你
    2020-11-22 04:14

    The latest version of SQL Server (2012) permits the following.

    SELECT 
        RowID, 
        Col1,
        SUM(Col1) OVER(ORDER BY RowId ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW) AS Col2
    FROM tablehh
    ORDER BY RowId
    

    or

    SELECT 
        GroupID, 
        RowID, 
        Col1,
        SUM(Col1) OVER(PARTITION BY GroupID ORDER BY RowId ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW) AS Col2
    FROM tablehh
    ORDER BY RowId
    

    This is even faster. Partitioned version completes in 34 seconds over 5 million rows for me.

    Thanks to Peso, who commented on the SQL Team thread referred to in another answer.

提交回复
热议问题