0

表:

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 | 到期时间


'due amt' 是所有 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))
4

1 回答 1

2
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 演示

于 2013-08-17T16:54:53.933 回答