我正在尝试用SQL编写一个查询来计算帐户之间转移的净资金。我在下面的一个名为Transactions的表中有我的测试数据。
Debit | From | To | Amount
---------------------------------
1 | ABC | BBC | $50
0 | BBC | ABC | $150
1 | ABC | CBC | $200
0 | CBC | ABC | $150
1 | ABC | EBC | $100
我的输出应该是上面的测试数据,如下所示:
From | To | Amount
--------------------------
BBC | ABC | $100
ABC | CBC | $50
ABC | EBC | $100
答案 0 :(得分:1)
这是一种方法
DECLARE @SampleData AS TABLE
(
Debit bit,
[From] varchar(10),
[To] varchar(10),
Amount int
)
INSERT INTO @SampleData
(
Debit,
[From],
[To],
Amount
)
VALUES
(1, 'ABC', 'BBC', 50 ),
(0, 'BBC', 'ABC', 150),
(1, 'ABC', 'CBC', 200),
(0, 'CBC', 'ABC', 150),
(1, 'ABC', 'EBC', 100)
;WITH temp AS
(
SELECT sd.[From], sd.[To], sd.Amount
FROM @SampleData sd
WHERE sd.Debit = 1
UNION ALL
SELECT sd.[To], sd.[From], -sd.Amount
FROM @SampleData sd
WHERE sd.Debit = 0
)
SELECT CASE WHEN sum(t.Amount) > 0 then t.[From] ELSe t.[To] End as [From],
CASE when sum(t.Amount) <= 0 then t.[From] ELSe t.[To] End as [To],
ABS(sum(t.Amount)) AS Amount
FROM temp t
GROUP BY t.[From], t.[To]
返回
From To Amount
----------------------
BBC ABC 100
ABC CBC 50
ABC EBC 100