0

Suppose I have the following data:

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

I want a resulting table that adds up the number column like this:

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

Basically, it adds the new number to the previous sum and is ordered by the ID.

Thanks in advance for the help.

Gordon Linoff
  • 1,242,037
  • 58
  • 646
  • 786
Farellia
  • 187
  • 1
  • 2
  • 14

3 Answers3

1

In SQL Server 2012+, you can just use the ANSI-standard cumulative sum function:

select id, characteristic, number, sum(number) over (order by id) as [sum]
from t;
Gordon Linoff
  • 1,242,037
  • 58
  • 646
  • 786
0

In SQL (>2012), you can just use the sum function:

select id, characteristic, number, sum(number) over (order by id) as [sum]
from t;
Lucas Trzesniewski
  • 50,214
  • 11
  • 107
  • 158
0

Std cumulative sum

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;
McNets
  • 10,352
  • 3
  • 32
  • 61