簡體   English   中英

如何將一列的第一條記錄與另一列的第二條記錄求和?

[英]How to Sum the 1st record of one column with the 2nd record of another column?

我正在嘗試將一列的第二條記錄與另一列的第一條記錄求和並將結果存儲在新列中

這是示例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-1Opening Balance相同
  2. 在接下來的幾個月中,其第二個月的Reserve for Month-2 =第Reserve for Month-1 +第Reserve for Month-1 Opening Balance for Month-2

您似乎想要一個累加的總和。 在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;

您可以進行自我加入。

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM