0

I am trying the Sum the 2nd record of one column with the 1st record of another column and store the result in a new column

Here is the example SQL Server table

Emp_Code   Emp_Name    Month          Opening_Balance   
 G101      Sam          1              1000              
 G102      James        2              -2500             
 G103      David        3              3000     
 G104      Paul         4              1800     
 G105      Tom          5              -1500      

I am trying to get the output as below on the new Reserve column

Emp_Code   Emp_Name    Month          Opening_Balance    Reserve
 G101      Sam          1              1000              1000       
 G102      James        2              -2500             -1500         
 G103      David        3              3000               1500
 G104      Paul         4              1800               3300
 G105      Tom          5              -1500              1800

Actually the rule for calculating the Reserve column is that

  1. For Month-1 it's the same as Opening Balance
  2. For rest of the months its Reserve for Month-2 = Reserve for Month-1 + Opening Balance for Month-2
Siyual
  • 16,415
  • 8
  • 44
  • 58
Shash
  • 11
  • 1

2 Answers2

3

You seem to want a cumulative sum. In SQL Server 2012+, you would do:

select t.*,
       sum(opening_balance) over (order by [Month]) as Reserve
from t;

In earlier versions, you would do this with a correlated subquery or apply:

select t.*,
       (select sum(t2.opening_balance) from t t2 where t2.[Month] <= t.[Month]) as reserve
from t;
Gordon Linoff
  • 1,242,037
  • 58
  • 646
  • 786
0

You can do a self join.

SELECT t.Emp_Code, t.Emp_Name, t.Month, t.Opening_Balance, t.Opening_Balance + n.Reserve
FROM Table1 t
JOIN Table2 n
ON t.Month = n.Month - 1
Kyle
  • 115
  • 2
  • 8