我正在使用MySQL,我有3个表,分别是客户,借方和贷方。每个客户都有一个或多个借方以及一个或多个贷方。现在,我要计算每个客户的总借方和总贷方,只显示那些总借方和总贷方不平衡的客户。谁能帮我?
最佳答案
一种想法是让两个聚合查询左连接起来,这两个查询计算每个客户的总贷方和借方,并过滤外部查询。
就像是:
select cus.*
from customers cus
left join (select customer_id, sum(amount) total_amount from credits group by customer_id) cre
on cre.customer_id = cus.customer_id
left join (select customer_id, sum(amount) total_amount from debits group by customer_id) deb
on deb.customer_id = cus.customer_id
where coalesce(cre.total_amount, 0) = coalesce(deb.customer_id, 0)
关于mysql - 如何找到在借方和贷方之间保持平衡的客户?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/59334192/