如何根据条件在 SQL 服务器中添加下一行和减去前一行
How to add next and subtract preceding row in SQL Server based on condition
我正在尝试根据 SQL 服务器中的 TranslationType
列计算累计总和。
示例数据:
Id TransactionType Value
-------------------------
1 Receipt 10
2 Issue 2
3 Receipt 10
4 Issue 5
5 Issue 3
我试过了,但我有一个问题,我得到的输出是错误的:
Id TransactionType DiffValue
-----------------------------
1 Receipt 10
2 Issue 8
3 Receipt 22
4 Issue 5
5 Issue 2
差值的期望输出:
Id TransactionType Value DiffValue
---------------------------------------
1 Receipt 10 10
2 Issue 2 8 if issue then 10-2
3 Receipt 10 18 if receipt then 10+8
4 Issue 5 13 if issue then 18-5
5 Issue 3 10 if issue then 13-3
SQL 创建脚本:
DROP TABLE #Temp
CREATE TABLE #Temp
(
Id INT,
TransactionType VARCHAR(50),
value INT,
)
INSERT INTO #Temp (Id, TransactionType, value)
VALUES (1, 'Receipt', 10), (2, 'Issue', 2), (3, 'Receipt', 10),
(4, 'Issue', 5), (5, 'Issue', 3)
SELECT * FROM #Temp
我的查询尝试:
SELECT
Id,
TransactionType,
CASE
WHEN TransactionType = 'Receipt'
THEN SUM(value) OVER (ORDER BY Id ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW)
ELSE LAG(value) OVER (ORDER BY Id) - value
END AS DiffValue
FROM
#Temp
你应该求和一个可以区分借方和贷方的CASE
表达式:
SELECT
Id,
TransactionType,
SUM(CASE WHEN TransactionType = 'Receipt' THEN value ELSE -1.0*value END)
OVER (ORDER BY Id ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW) AS DiffValue
FROM #Temp
ORDER BY Id;
我正在尝试根据 SQL 服务器中的 TranslationType
列计算累计总和。
示例数据:
Id TransactionType Value
-------------------------
1 Receipt 10
2 Issue 2
3 Receipt 10
4 Issue 5
5 Issue 3
我试过了,但我有一个问题,我得到的输出是错误的:
Id TransactionType DiffValue
-----------------------------
1 Receipt 10
2 Issue 8
3 Receipt 22
4 Issue 5
5 Issue 2
差值的期望输出:
Id TransactionType Value DiffValue
---------------------------------------
1 Receipt 10 10
2 Issue 2 8 if issue then 10-2
3 Receipt 10 18 if receipt then 10+8
4 Issue 5 13 if issue then 18-5
5 Issue 3 10 if issue then 13-3
SQL 创建脚本:
DROP TABLE #Temp
CREATE TABLE #Temp
(
Id INT,
TransactionType VARCHAR(50),
value INT,
)
INSERT INTO #Temp (Id, TransactionType, value)
VALUES (1, 'Receipt', 10), (2, 'Issue', 2), (3, 'Receipt', 10),
(4, 'Issue', 5), (5, 'Issue', 3)
SELECT * FROM #Temp
我的查询尝试:
SELECT
Id,
TransactionType,
CASE
WHEN TransactionType = 'Receipt'
THEN SUM(value) OVER (ORDER BY Id ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW)
ELSE LAG(value) OVER (ORDER BY Id) - value
END AS DiffValue
FROM
#Temp
你应该求和一个可以区分借方和贷方的CASE
表达式:
SELECT
Id,
TransactionType,
SUM(CASE WHEN TransactionType = 'Receipt' THEN value ELSE -1.0*value END)
OVER (ORDER BY Id ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW) AS DiffValue
FROM #Temp
ORDER BY Id;