How to get cumulative sum

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

    The SQL solution wich combines "ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW" and "SUM" did exactly what i wanted to achieve. Thank you so much!

    If it can help anyone, here was my case. I wanted to cumulate +1 in a column whenever a maker is found as "Some Maker" (example). If not, no increment but show previous increment result.

    So this piece of SQL:

    SUM( CASE [rmaker] WHEN 'Some Maker' THEN  1 ELSE 0 END) 
    OVER 
    (PARTITION BY UserID ORDER BY UserID,[rrank] ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW) AS Cumul_CNT
    

    Allowed me to get something like this:

    User 1  Rank1   MakerA      0  
    User 1  Rank2   MakerB      0  
    User 1  Rank3   Some Maker  1  
    User 1  Rank4   Some Maker  2  
    User 1  Rank5   MakerC      2
    User 1  Rank6   Some Maker  3  
    User 2  Rank1   MakerA      0  
    User 2  Rank2   SomeMaker   1  
    

    Explanation of above: It starts the count of "some maker" with 0, Some Maker is found and we do +1. For User 1, MakerC is found so we dont do +1 but instead vertical count of Some Maker is stuck to 2 until next row. Partitioning is by User so when we change user, cumulative count is back to zero.

    I am at work, I dont want any merit on this answer, just say thank you and show my example in case someone is in the same situation. I was trying to combine SUM and PARTITION but the amazing syntax "ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW" completed the task.

    Thanks! Groaker

提交回复
热议问题