I have three tables, a purchase order table, an items ordered table, and an invoice table. I want to select records from the purchase orders based on various criteria (eg vendor, or date, etc) and then get the SUM of the items ordered from the second table, and the SUM of the invoices (if any exist yet) from the third table. Is this possible with a single select statement?
Here is one of my trial queries that seems to be close to what I am looking for. Depending on how I apply (phrase) the 'group by' clause and the table being grouped, it sometimes produces corect results for one of the sums or the other:
SELECT po.ponum, po.poDate, po.vendor, po.status,
SUM(item.qty*item.cost) AS itemtotal, SUM(invoice.cost) AS invoicetotal
FROM po LEFT JOIN item ON po.ponum=item.ponum
LEFT JOIN invoice ON po.ponum=poinvoice.ponum
WHERE po.status='open' AND
((po.pon BETWEEN $poNumLo AND $poNumHi) OR (po.poDate BETWEEN '$poDateLo' AND '$poDateHi'))
GROUP BY item.pon
The actual application and tables are a bit more complex, but I simplified it here for clarity.
Thanks for any advice!
Here is one of my trial queries that seems to be close to what I am looking for. Depending on how I apply (phrase) the 'group by' clause and the table being grouped, it sometimes produces corect results for one of the sums or the other:
SELECT po.ponum, po.poDate, po.vendor, po.status,
SUM(item.qty*item.cost) AS itemtotal, SUM(invoice.cost) AS invoicetotal
FROM po LEFT JOIN item ON po.ponum=item.ponum
LEFT JOIN invoice ON po.ponum=poinvoice.ponum
WHERE po.status='open' AND
((po.pon BETWEEN $poNumLo AND $poNumHi) OR (po.poDate BETWEEN '$poDateLo' AND '$poDateHi'))
GROUP BY item.pon
The actual application and tables are a bit more complex, but I simplified it here for clarity.
Thanks for any advice!