2016-07-06 51 views
0

我想求和一列的第二个记录与另一列的第一个记录,并把结果保存在一个新的列如何将一列的第一条记录与另一列的第二条记录相加?

这里是例如SQL Server表

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  

我想得到的输出如下的新Reserve

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 

其实计算Reserve列的规则是

  1. 对于Month-1它一样Opening Balance
  2. 可以看到月份余下时间的Reserve for Month-2 = Reserve for Month-1 + Opening Balance for Month-2
+0

请用SQL Server版本标记您的问题。 –

+3

[在SQL Server中计算运行总计]的可能重复(http://stackoverflow.com/questions/860966/calculate-a-running-total-in-sql-server) –

回答

3

你似乎想的累加值。在SQL Server 2012+,你会怎么做:

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

在早期版本中,您将与相关子查询或apply做到这一点:

select t.*, 
     (select sum(t2.opening_balance) from t t2 where t2.[Month] <= t.[Month]) as reserve 
from t; 
0

你可以做一个自连接。

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