[英]How to get SUM of a column of a child table when query parent table?
我有两张桌子
账户表(账户)
id name
1 Account 1
2 Account 2
3 Account 3
4 Account 2
交易表(交易)
id account_id type amount datetime
1 1 credit 500 2020-04-01 06:00:00
2 1 credit 300 2020-04-01 06:00:00
3 2 credit 100 2020-04-01 06:00:00
4 2 debit 50 2020-04-01 06:00:00
5 1 debit 600 2020-04-01 06:00:00
6 3 credit 1000 2020-04-01 06:00:00
7 1 credit 100
我的目标是在一个查询中获取帐户id, name, balance
。 余额将从交易表中计算SUM of Credit Amount - SUM of Debit Amount
总和SUM of Credit Amount - SUM of Debit Amount
给定帐户SUM of Credit Amount - SUM of Debit Amount
总和。
目标输出
id name balance
1 Account 1 300
2 Account 2 50
3 Account 3 1000
4 Account 4 0
可能的查询
SELECT id, name, ((SELECT SUM(amount) FROM transaction WHERE type = 'credit' AND account_id = {ACCOUNT_ID} ) - (SELECT SUM(amount) FROM transaction WHERE type = 'debit' AND account_id = {ACCOUNT_ID} )) as balance
是否可以在一个查询中执行此操作,如果是,如何执行此操作。
您可以在派生表中进行聚合,以避免必须按顶级中的许多字段进行分组的问题。 例如:
SELECT a.id, a.name, COALESCE(b.balance, 0) AS balance
FROM account a
LEFT JOIN (
SELECT account_id,
SUM(CASE WHEN type='credit' THEN amount ELSE 0 END) -
SUM(CASE WHEN type='debit' THEN amount ELSE 0 END) AS balance
FROM transaction
GROUP BY account_id
) b ON b.account_id = a.id
输出:
id name balance
1 Account 1 300
2 Account 2 50
3 Account 3 1000
4 Account 2 0
您需要将account
left join
到transaction
以便您可以按每个帐户分组并根据type
有条件地总结amount
:
select
a.id, a.name,
sum(case when type = 'credit' then 1 else -1 end * coalesce(t.amount, 0)) balance
from account a left join transaction t
on t.account_id = a.id
group by a.id, a.name
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.