创建累积总和列

时间:2011-12-22 14:11:03

标签: sql-server sum

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

num
1
5
6
8
2
3

我需要一个查询才能做到这一点: 期望的输出:  (应该排序并有累积总和列)

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

Mysql 我有

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

我在这个link但在MySqlServer

中选择了这个例子

2 个答案:

答案 0 :(得分:2)

试试这个:

SELECT num,(SELECT SUM(num) FROM tab WHERE num<=t.num) AS CumulativeSum
FROM tab t

答案 1 :(得分:0)

由于num不是唯一的,你可能需要使用row_number来获取一个唯一的数字,然后做总和:

declare @t as table (num int)

insert into @t (num) values (1)
insert into @t (num) values (5)
insert into @t (num) values (6)
insert into @t (num) values (7)
insert into @t (num) values (2)
insert into @t (num) values (3)

;with rows as (
    select
        num,
        ROW_NUMBER() over (order by num) as Row
    from @t
)
select num, (select sum(num) from rows where row <= r.row)
from rows r