How to get cumulative sum

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

    Lets first create a table with dummy data -->

    Create Table CUMULATIVESUM (id tinyint , SomeValue tinyint)
    
    **Now let put some data in the table**
    
    Insert Into CUMULATIVESUM
    
    Select 1, 10 union 
    Select 2, 2  union
    Select 3, 6  union
    Select 4, 10 
    

    here I am joining same table (SELF Joining)

    Select c1.ID, c1.SomeValue, c2.SomeValue
    From CumulativeSum c1,  CumulativeSum c2
    Where c1.id >= c2.ID
    Order By c1.id Asc
    

    RESULT :

    ID  SomeValue   SomeValue
    1   10          10
    2   2           10
    2   2            2
    3   6           10
    3   6            2
    3   6            6
    4   10          10
    4   10           2
    4   10           6
    4   10          10
    

    here we go now just sum the Somevalue of t2 and we`ll get the ans

    Select c1.ID, c1.SomeValue, Sum(c2.SomeValue) CumulativeSumValue
    From CumulativeSum c1,  CumulativeSum c2
    Where c1.id >= c2.ID
    Group By c1.ID, c1.SomeValue
    Order By c1.id Asc
    

    FOR SQL SERVER 2012 and above(Much better perform)

    Select c1.ID, c1.SomeValue, 
    SUM (SomeValue) OVER (ORDER BY c1.ID )
    From CumulativeSum c1
    Order By c1.id Asc
    

    Desired Result

    ID  SomeValue   CumlativeSumValue
    1   10          10
    2   2           12
    3   6           18
    4   10          28
    
    Drop Table CumulativeSum
    

    Clear the dummytable

提交回复
热议问题