[英]SQL Server - Add or Subtract from Previous Value
I'm trying to get the balance from this data 我正在尝试从此数据中获取余额
Date Logged Closed
-------------- ----------- -----------
1-Jan-2016 0 0
2-Jan-2016 8 7
3-Jan-2016 8 8
4-Jan-2016 25 11
5-Jan-2016 20 16
6-Jan-2016 14 13
7-Jan-2016 10 12
8-Jan-2016 9 7
9-Jan-2016 12 12
10-Jan-2016 3 4
The expected output is 预期的输出是
Date Logged Closed Balance
-------------- ----------- ----------- ----------
1-Jan-2016 0 0 0
2-Jan-2016 8 7 1
3-Jan-2016 8 8 1
4-Jan-2016 25 11 15
5-Jan-2016 20 16 19
6-Jan-2016 14 13 20
7-Jan-2016 10 12 18
8-Jan-2016 9 7 20
9-Jan-2016 12 12 20
10-Jan-2016 3 4 27
The formula is BALANCE = PREVIOUSBALANCE + LOGGED - CLOSED. 公式为BALANCE = PREVIOUSBALANCE + LOGGED-CLOSED。
Example formula : 公式示例:
Jan 5 Balance (15) = 1(prevBalance) + 25(currentLogged) - 11(currentClosed)
I've tried this formula but does not get anywhere close to the desired result. 我已经尝试过此公式,但无法达到所需结果。
WITH CTE AS (
SELECT
rownum = ROW_NUMBER() OVER (ORDER BY Date),
Date, Logged, Closed
FROM Table
)
SELECT
(prev.Logged - prev.Closed)+ (a.Logged-a.Closed) as [Balance]
FROM CTE
LEFT JOIN CTE prev ON prev.rownum = CTE.rownum - 1
Other references used 使用的其他参考
SQL Server - Calculate current row value using previous row value SQL Server-使用上一个行值计算当前行值
http://blog.sqlauthority.com/2013/09/22/sql-server-how-to-access-the-previous-row-and-next-row-value-in-select-statement/ http://blog.sqlauthority.com/2013/09/22/sql-server-how-to-access-the-previous-row-and-next-row-value-in-select-statement/
You can do this using Window function sum
. 您可以使用Window函数
sum
来执行此操作。
Try this: 尝试这个:
select
t.*,
sum(logged - closed) over (order by date) balance
from your_table t;
The problem of your answer is the Balanced of the previous row is not available when you calculate (SQL-Server 's All-at-once principle). 您的问题是计算时,上一行的Balanced不可用(SQL-Server的一次性算法)。 Your question has a hidden requirement of calculating sum of all the previous rows, ordered by date.
您的问题有一个隐含的要求,即按日期顺序计算所有先前行的总和。
Try this (only applied for SQL Server 2012 and beyond) 试试看(仅适用于SQL Server 2012及更高版本)
SELECT
[Date], Logged, Closed,
SUM(Logged) OVER (ORDER BY [Date] ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW)
- SUM (Closed) OVER (ORDER BY [Date] ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW) AS Balance
FROM
<<Table>>
For previous version: 对于以前的版本:
SELECT
t.[Date], t.Logged, t.Closed, sub.L - sub.C AS Balanced
FROM
<<Table>> t
CROSS APPLY ( SELECT SUM(Logged) AS L, SUM(Closed) AS c FROM <<Table>> WHERE [Date] <= t.[Date]) AS sub
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.