On Tue, 07 Dec 2004 19:53:58 GMT, Paul Owen wrote:
current sql is
(snip)returns the right info but for all people
Hi Paul,
Are you sure? You should get errors because people.Name and address.city
are in the select (not in an aggregate) but not in the group by. And
because the address table is not in the from clause at all.
Assuming these errors were made when you copied the query, you should
still get the wrong results. Have you tested it with a combination of a
person with two payments and two invoices? I think you'll the values will
be double what you expect. And it gets much worse if you have five
payments and ten invoices....
Try this one:
SELECT ID, PayTotal, InvTotal,
InvTotal - PayTotal AS StillOwed
FROM (SELECT people.ID,
COALESCE((SELECT SUM(amount)
FROM payments
WHERE payments.ID = people.ID),0) AS PayTotal,
COALESCE((SELECT SUM(amount)
FROM invoices
WHERE invoices.ID = people.ID),0) AS InvTotal
FROM people
GROUP BY people.ID) AS x
WHERE InvTotal > PayTotal
or this one:
SELECT people.ID,
COALESCE (paytot.Total,0) AS PayTotal,
COALESCE (invtot.Total,0) AS InvTotal,
COALECSE (invtot.Total,0)
- COALESCE (paytot.Total,0) AS StillOwed
FROM people
LEFT JOIN (SELECT ID, SUM(amount) AS Total
FROM payments
GROUP BY ID) AS paytot
ON paytot.ID = people.ID
LEFT JOIN (SELECT ID, SUM(amount) AS Total
FROM invoices
GROUP BY ID) AS invtot
ON invtot.ID = people.ID
WHERE COALECSE (invtot.Total,0) > COALESCE (paytot.Total,0)
(both queries untested!)
Best, Hugo
--
(Remove _NO_ and _SPAM_ to get my e-mail address)