Create a Cumulative Sum Column in MySQL

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

    select id,count,sum(count)over(order by count desc) as cumulative_sum from tableName;

    I have used the sum aggregate function on the count column and then used the over clause. It sums up each one of the rows individually. The first row is just going to be 100. The second row is going to be 100+50. The third row is 100+50+10 and so forth. So basically every row is the sum of it and all the previous rows and the very last one is the sum of all the rows. So the way to look at this is each row is the sum of the amount where the ID is less than or equal to itself.

提交回复
热议问题