Create a Cumulative Sum Column in MySQL

前端 未结 9 1953
青春惊慌失措
青春惊慌失措 2020-11-22 00:05

I have a table that looks like this:

id   count
1    100
2    50
3    10

I want to add a new column called cumulative_sum, so the table wou

9条回答
  •  一整个雨季
    2020-11-22 00:16

      select t1.id, t1.count, SUM(t2.count) cumulative_sum
        from table t1 
            join table t2 on t1.id >= t2.id
        group by t1.id, t1.count
    

    Step by step:

    1- Given the following table:

    select *
    from table t1 
    order by t1.id;
    
    id  | count
     1  |  11
     2  |  12   
     3  |  13
    

    2 - Get information by groups

    select *
    from table t1 
        join table t2 on t1.id >= t2.id
    order by t1.id, t2.id;
    
    id  | count | id | count
     1  | 11    | 1  |  11
    
     2  | 12    | 1  |  11
     2  | 12    | 2  |  12
    
     3  | 13    | 1  |  11
     3  | 13    | 2  |  12
     3  | 13    | 3  |  13
    

    3- Step 3: Sum all count by t1.id group

    select t1.id, t1.count, SUM(t2.count) cumulative_sum
    from table t1 
        join table t2 on t1.id >= t2.id
    group by t1.id, t1.count;
    
    
    id  | count | cumulative_sum
     1  |  11   |    11
     2  |  12   |    23
     3  |  13   |    36
    

提交回复
热议问题