2016-07-06 2 views
0

내가 다른 컬럼의 첫번째 레코드 합계를 한 열 번째 기록을 시도하고 새 열 여기한 열의 첫 번째 레코드와 다른 열의 두 번째 레코드를 더하는 방법은 무엇입니까?

에 결과를 저장하고하는 것은 내가하려고

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  

예제 SQL Server 테이블을이다 새로운 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 열을 산출하기위한 규칙은

0 그
  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 서버 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 
관련 문제