1

I have the following 3 columns. Col3 first value is always 0. The values after that is always going to be the sum of col2 + col3 of the previous record.

col1  col2   col3
1     6.48   0
2     1.95
3     1.66
4     .84
5     .56
6     1.24

So the final values would be as follows:

col1  col2     col3
   1     6.48    0
   2     1.95    6.48
   3     1.66    8.43
   4     .84    10.09
   5     .56    10.93
   6     1.24   11.49

Does anyone know if this can be done without a cursor in SQL Server?

Ilyes
  • 14,640
  • 4
  • 29
  • 55
yanci
  • 163
  • 1
  • 13

1 Answers1

3

You could use windowed SUM and subtract current value:

SELECT *, SUM(col2) OVER(ORDER BY col1)-col2 AS col3
FROM tab;

db<>fiddle demo

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
Lukasz Szozda
  • 162,964
  • 23
  • 234
  • 275