【问题标题】:How can I find customers which are balanced in their debit and credits?如何找到借方和贷方平衡的客户?
【发布时间】:2019-12-15 09:42:47
【问题描述】:

我正在使用 MySQL,我有 3 个表,分别是客户、借方和贷方。每个客户都有一个或多个借方和一个或多个贷方。现在我想计算每个客户的总借方和总贷方,并只显示那些总借方和总贷方不平衡的客户。谁能帮帮我?

【问题讨论】:

  • 从表格中添加一些示例。并添加预期结果。
  • 我在 Stack Overflow 中添加图片和代码时遇到了一些问题。我将尝试在下一个问题中添加它们。

标签: mysql sql group-by


【解决方案1】:

一个想法是左连接两个聚合查询,计算每个客户的总贷记和借记,并在外部查询中进行过滤。

类似:

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)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多