SQL Server:按顺序添加列

时间:2017-01-24 23:11:17

标签: sql sql-server

假设我有以下数据:

ID        Characteristic     Number
1               A               3
2               B               4
3               A               1
4               A               6

我想要一个结果表,将这样的数字列加起来:

ID        Characteristic     Number          Sum
1               A               3             3
2               B               4             7
3               A               1             8
4               A               6             14

基本上,它将新数字添加到前一个总和,并按ID排序。

提前感谢您的帮助。

3 个答案:

答案 0 :(得分:1)

在SQL Server 2012+中,您只需使用ANSI标准累积和函数:

select id, characteristic, number, sum(number) over (order by id) as [sum]
from t;

答案 1 :(得分:0)

在SQL(> 2012)中,您只需使用sum函数:

select id, characteristic, number, sum(number) over (order by id) as [sum]
from t;

答案 2 :(得分:0)

标准累积金额

select t1.*, SUM(t2.Nuber) as sum
from table t1
inner join table t2 on t1.id >= t2.id
group by t1.id, t1.Number
order by t1.id;