I have a table of invoices with costs associated.
I have a linked table with misc costs as well
relationship is 1 to many misc costs
When I do a SUM() and multiple rows exist on RIGHT table, the values in the LEFT table are multiplied by the number of rows found.
DB Fiddle:
Original query with incorrect results for LABOUR, PARTS, POLS and SUBLET:
“`
SELECT SUM(ad.labour_cost) AS LABOUR,
SUM(ad.part_cost) AS PARTS,
SUM(ad.pol_cost) AS POLS,
SUM(ad.sublet_cost) AS SUBLET,
SUM(am.misc_sales_amt) AS MISC
FROM AdvisorSalesData ad
LEFT JOIN AdvisorMiscSalesData am
ON (ad.customer_id=am.customer_id AND ad.invoice_no=am.invoice_no)
WHERE ad.customer_id IN (3)
Adjusted query – with incorrect result for MISC (NULL):
“`
SELECT SUM(ad.labour_cost) AS LABOUR,
SUM(ad.part_cost) AS PARTS,
SUM(ad.pol_cost) AS POLS,
SUM(ad.sublet_cost) AS SUBLET,
(SELECT SUM(misc_sales_amt) FROM AdvisorMiscSalesData WHERE customer_id IN (3) AND invoice_no=ad.invoice_no ) AS MISC
FROM AdvisorSalesData ad
WHERE ad.customer_id IN (3)
How can I adjust to get the correct results for all 5 columns in one single query?