在MySQL中创建累积和列

时间:2011-10-02 21:04:02

标签: mysql sql

样本表ID :( num是一个键,因此不会有任何重复)

num
1
5
6
8
2
3

期望的输出:
(应该排序并有累积总和列)

num cumulative
1    1
2    3
3    6
5    11
6    17
8    25

这是我得到的一个解决方案:

select a.num, sum(b.num) from ID a, ID b where b.num <= a.num group by a.num order by a.num;

4 个答案:

答案 0 :(得分:7)

您可以使用temporary variable计算累积总和:

SELECT  a.num,
   (@s := @s + a.num) AS cumulative
FROM ID a, (SELECT @s := 0) dm
ORDER BY a.num;

答案 1 :(得分:3)

我想我找到了解决方案。

Select num as n, 
       (select sum(num) from ID where num <= n)
from ID order by n;

答案 2 :(得分:0)

因为这些答案我已经在我的项目中测试过,实际上我想知道哪一个更快,所以我也在这里发布了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

答案 3 :(得分:0)

自MySQL 8开始,理想情况下使用window functions计算累计和。对于您的情况,请运行:

SELECT num, SUM(num) OVER (ORDER BY num) cumulative
FROM id