Create a Cumulative Sum Column in MySQL

前端 未结 9 1941
青春惊慌失措
青春惊慌失措 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:19

    If performance is an issue, you could use a MySQL variable:

    set @csum := 0;
    update YourTable
    set cumulative_sum = (@csum := @csum + count)
    order by id;
    

    Alternatively, you could remove the cumulative_sum column and calculate it on each query:

    set @csum := 0;
    select id, count, (@csum := @csum + count) as cumulative_sum
    from YourTable
    order by id;
    

    This calculates the running sum in a running way :)

提交回复
热议问题