How to get cumulative sum

前端 未结 16 2365
遇见更好的自我
遇见更好的自我 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:13

    select t1.id, t1.SomeNumt, SUM(t2.SomeNumt) as sum
    from @t t1
    inner join @t t2 on t1.id >= t2.id
    group by t1.id, t1.SomeNumt
    order by t1.id
    

    SQL Fiddle example

    Output

    | ID | SOMENUMT | SUM |
    -----------------------
    |  1 |       10 |  10 |
    |  2 |       12 |  22 |
    |  3 |        3 |  25 |
    |  4 |       15 |  40 |
    |  5 |       23 |  63 |
    

    Edit: this is a generalized solution that will work across most db platforms. When there is a better solution available for your specific platform (e.g., gareth's), use it!

提交回复
热议问题