2013-11-10 48 views
2

我試圖找到尚未全額支付全部費用(仍有餘額)的客人的名單。查詢實體的到期餘額和到期日

我想要顯示像這樣:

 
1231231(reservation id) - John Doe(guest name) 2013-11-17(date due) 153.14(balance due) 

沒有的()過程。

我修了一下,但還是找不到滿意的查詢。

這裏是鏈接到SQLFiddle

如果我沒有提供足夠的信息,請讓我知道。

回答

3

你在尋找類似的東西嗎?

SELECT r.id, 
     CONCAT(g.fname, ' ', g.lname) guest_name, 
     r.arrival date_due, 
     r.total_price - COALESCE(p.payment_amt, 0) balance_due 
    FROM reservations r JOIN guests g 
    ON r.guest = g.id LEFT JOIN 
(
    SELECT reservation, SUM(payment_amt) payment_amt 
    FROM payments 
    GROUP BY reservation 
) p 
    ON r.id = p.reservation 
HAVING balance_due > 0 

樣本輸出(基於所提供的樣本的數據):

 
|  ID | GUEST_NAME |      DATE_DUE | BALANCE_DUE | 
|---------|------------|---------------------------------|-------------| 
| 1000023 | John Doe | November, 09 2013 00:00:00+0000 |  40.5 | 
| 1000022 | John Doe | November, 09 2013 00:00:00+0000 |  40.5 | 
| 1000018 | John Doe | November, 01 2013 00:00:00+0000 |   54 | 
| 1000019 | John Doe | November, 08 2013 00:00:00+0000 |   54 | 
| 1000020 | Mary Jane | November, 08 2013 00:00:00+0000 |   54 | 
| 1000021 | Mary Jane | November, 08 2013 00:00:00+0000 |   54 | 

這裏是SQLFiddle演示