我在Postgres数据库上使用pgAdmin。我正在尝试获得以下结果(金额是随机的):
为此,我需要查询以下两个表:帐户和交易
我不确定如何将总和(金额)结果分成1列。我尝试了以下方法:
select SUM(
CASE WHEN debit_account_id = 1 then amount
when credit_account_id = 1 then amount * (-1) else 0 end),
SUM(
CASE WHEN debit_account_id = 2 then amount
when credit_account_id = 2 then amount * (-1) else 0 end)
from transactions
where entity_id = 1
,依此类推,直到account_id6。这将为我提供每个帐户的正确金额,但每个结果都在新列中。如何将其结合起来,使结果看起来像上面的示例?
答案 0 :(得分:1)
您可以使用UNION ALL
。
select debit_account_id account_id, -amount from transactions
union all
select credit_account_id account_id, amount from transactions;
现在您将数据放在一栏中
答案 1 :(得分:0)
我将在不同的查询中将每个帐户的借方和贷方加起来,然后将它们加入帐户表中:
SELECT account_name, sum_credut - sum_debit AS balance
FROM accounts a
JOIN (SELECT credit_account_id, SUM(amount)
FROM transfer
GROUP BY credit_account_id) c ON a.id = c.credit_account_id
JOIN (SELECT debit_account_id, SUM(amount)
FROM transfer
GROUP BY debit_account_id) d ON a.id = d.debit_account_id
答案 2 :(得分:0)
我为此建议一个横向连接:
select a.account_name,
sum(v.signed_amount) as total_amount
from transactions t left join lateral
(values (t.debit_account_id, t.amount),
(t.credit_account_id, - t.amount)
) v(account_id, signed_amount) join
account a
on a.id = v.account_id
group by a.account_name;
我在任何表格中都没有看到entity_id
,所以我不知道那是哪里来的。