[英]How to Sum the 1st record of one column with the 2nd record of another column?
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 这是示例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
I am trying to get the output as below on the new Reserve
column 我正在尝试在新的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
Actually the rule for calculating the Reserve
column is that 实际上,计算“ Reserve
列的规则是
Month-1
it's the same as Opening Balance
第Month-1
与Opening Balance
相同 Reserve for Month-2
= Reserve for Month-1
+ Opening Balance for Month-2
在接下来的几个月中,其第二个月的Reserve for Month-2
=第Reserve for Month-1
+第Reserve for Month-1
Opening Balance for Month-2
You seem to want a cumulative sum. 您似乎想要一个累加的总和。 In SQL Server 2012+, you would do: 在SQL Server 2012+中,您可以执行以下操作:
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
: 在早期版本中,您可以使用相关子查询来执行此操作,也可以apply
:
select t.*,
(select sum(t2.opening_balance) from t t2 where t2.[Month] <= t.[Month]) as reserve
from t;
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.