[英]How to get SUM of a column of a child table when query parent table?
I have two tables我有两张桌子
Account Table (account)账户表(账户)
id name
1 Account 1
2 Account 2
3 Account 3
4 Account 2
Transaction Table (transaction)交易表(交易)
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
My target is to get account id, name, balance
in one query.我的目标是在一个查询中获取帐户
id, name, balance
。 The balance will be calculated from the transaction table as SUM of Credit Amount - SUM of Debit Amount
for a given account.余额将从交易表中计算
SUM of Credit Amount - SUM of Debit Amount
总和SUM of Credit Amount - SUM of Debit Amount
给定帐户SUM of Credit Amount - SUM of Debit Amount
总和。
Target Output目标输出
id name balance
1 Account 1 300
2 Account 2 50
3 Account 3 1000
4 Account 4 0
Possible Query可能的查询
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
Is it possible to do this in one query and If yes How to do it.是否可以在一个查询中执行此操作,如果是,如何执行此操作。
You could do the aggregation in a derived table to avoid the issues of having to group by a lot of fields in the top level.您可以在派生表中进行聚合,以避免必须按顶级中的许多字段进行分组的问题。 For example:
例如:
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
Output:输出:
id name balance
1 Account 1 300
2 Account 2 50
3 Account 3 1000
4 Account 2 0
You need a left join
of account
to transaction
so you can group by each account and conditionally sum the amount
depending on the type
:您需要将
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.