表格:
cust table:
cust_id, name, etc
bill table:
bill_id, cust_id, amt, due_date, status (open/closed)
payment table:
payment_id, bill_id, amt etc
客户可以通过分期付款的方式一次性结清账单。因此,一个 bill_id 可能与 payment_ids 相关。
我无法生成此记录集:
<小时/>cust_id |到期金额
<小时/>“到期金额”是所有 bill.amts 的总和 - 所有 payment.amts 且状态为开放的总和。
账单表
bill_id cust_id amt status
1 18 200 open
2 18 200 open
3 17 200 open
4 17 200 open
5 17 200 open
6 17 200 closed
付款表
payment_id bill_id cust_id amt
1 1 18 50
2 2 18 40
3 3 17 10
预期输出
cust_id due_amt hint/how
17 590 (600-10) .. 600 -> because one is closed
18 310 (400-(50+40))
最佳答案
select c.cust_id, sum(b.amt) - sum(p.amt) as due_amt
from cust c
left join bill b on b.cust_id = c.cust_id and b.status = 'open'
left join payment p on p.bill_id = b.bill_id
group by c.cust_id
SQLFiddle demo
关于mysql - 如何组合多对多加入?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18291185/