[英]Calculate account balance history in PostgreSQL
我正在嘗試使用 SQL 獲取帳戶的余額歷史記錄。 我在PostgreSQL中的表如下所示:
id sender_id recipient_id amount_money
--- ----------- ---------------------- -----------------
1 1 2 60.00
2 1 2 15.00
3 2 1 35.00
所以 ID 號為 2 的用戶目前在他的帳戶中有 40 美元。 我想使用 sql 得到這個結果:
[60, 75, 40]
是否可以在 postgres 中使用 sql 做這樣的事情?
要獲得滾動余額,您可以根據id
是收件人還是SUM
對金額(最多並包括當前行)求和:
SELECT id, sender_id, recipient_id, amount_money,
SUM(CASE WHEN recipient_id = 2 THEN amount_money
WHEN sender_id = 2 THEN -amount_money
END) OVER (ORDER BY id) AS balance
FROM transactions
Output:
id sender_id recipient_id amount_money balance
1 1 2 60.00 60.00
2 1 2 15.00 75.00
3 2 1 35.00 40.00
如果你想要一個數組,你可以使用array_agg
和上面的查詢作為派生表:
SELECT array_agg(balance)
FROM (
SELECT SUM(CASE WHEN recipient_id = 2 THEN amount_money
WHEN sender_id = 2 THEN -amount_money
END) OVER (ORDER BY id) AS balance
FROM transactions
) t
Output:
[60,75,40]
如果您想更復雜並支持多個帳戶的余額,則需要將初始數據拆分為帳戶 id,當 id 為接收者時添加,當發送者時減去。 您可以使用CTE
生成適當的數據:
WITH trans AS (
SELECT id, sender_id AS account_id, -amount_money AS amount
FROM transactions
UNION ALL
SELECT id, recipient_id AS account_id, amount_money AS amount
FROM transactions
),
balances AS (
SELECT id, account_id, ABS(amount),
SUM(amount) OVER (PARTITION BY account_id ORDER BY id) AS balance
FROM trans
)
SELECT account_id, ARRAY_AGG(balance) AS bal_array
FROM balances
GROUP BY account_id
Output:
account_id bal_array
1 [-60,-75,-40]
2 [60,75,40]
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.