-2

I want to make a table in SQL, based on a table that looks like this

Table 1

row    cost
1       25
2       15
3       10
4       12
...     ...

In the new table for each row the column SUM is the sum of all cost whose rows are less than or equal to the one in the new table.

Table 2

row    SUM
1       25 
2       40 is the sum of row 1 and 2 from Table 1
3       50 is the sum of row 1, 2 and 3 from Table 1
4       62 is the sum of row 1, 2, 3 and 4 from Table 1
...     ...

Do you have any idea how to do this in the most efficient way without creating a lot of joins?

1 Answers1

1

You want a cumulative sum:

select row, sum(cost) over (order by row) as running_sum
from table1;
Gordon Linoff
  • 1,242,037
  • 58
  • 646
  • 786