你在尋找類似的東西嗎?
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演示