I’m trying to write a SELECT query that joins multiple one-to-many tables. A table named disbursements has both a LEFT JOIN to a table named contacts (because a contact can have many disbursements) and a LEFT JOIN to a table named pledges (because a pledge (promise of payment) can have multiple disbursements (actual payments).
My question is how can I pull records that list contacts, their pledges, and the pledge balance (the sum of disbursements towards a pledge subtracted from the pledge)?
Here is what I got so far:
SELECT *, (p.pl_amount - SUM(disb_amount)) as balance FROM disbursements d
LEFT JOIN contacts c on c.c_no = d.c_no
LEFT JOIN pledges p on d.pl_no = p.pl_no
GROUP BY d.disb_no
HAVING balance > 500
ORDER BY c.c_last
Thank you in advance
What you’ll probably want to do is put the
contactstable in theFROMclause instead of in aLEFT JOINsince you still want to retrieve contacts even when they don’t have any disbursements/pledges.Also since you seem to only want contacts that have a pledge balance >
500, aLEFT JOINisn’t necessary unless you also want to retrieve contacts that DON’T have any pledges OR have a balance >500. I used a regular (inner)JOINinstead:Try this: