繁体   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