Creating a cumulative sum column in MySQL

前端 未结 4 409
野性不改
野性不改 2020-12-21 04:07

Sample table ID: (num is a key so there wouldn\'t be any duplicates)

num
1
5
6
8
2
3

Desired output:
(Should be sorted and have a cumul

相关标签:
4条回答
  • 2020-12-21 04:19

    You can use a temporary variable to calculate the cumulative sum:

    SELECT  a.num,
       (@s := @s + a.num) AS cumulative
    FROM ID a, (SELECT @s := 0) dm
    ORDER BY a.num;
    
    0 讨论(0)
  • 2020-12-21 04:21

    I think I figured out the solution.

    Select num as n, 
           (select sum(num) from ID where num <= n)
    from ID order by n;
    
    0 讨论(0)
  • 2020-12-21 04:22

    as these answer i already tested in my project and actually i want to know which one is faster so i also posted this here which one is faster

    declare @tmp table(ind int identity(1,1),col1 int)
    insert into @tmp
    select 2
    union
    select 4
    union
    select 7
    union 
    
    select 5
    union
    select 8
    union 
    select 10
    
    
     SELECT t1.col1,sum( t2.col1)
        FROM @tmp AS t1 LEFT JOIN @tmp t2 ON t1.ind>=t2.ind
        group by t1.ind,t1.col1
    
    select t1.col1,(select sum(col1) from  @tmp as t2 where t2.ind<=t1.ind)
    from @tmp as t1
    
    0 讨论(0)
  • 2020-12-21 04:32

    Since MySQL 8, cumulative sums are ideally calculated using window functions. In your case, run:

    SELECT num, SUM(num) OVER (ORDER BY num) cumulative
    FROM id
    
    0 讨论(0)
提交回复
热议问题