MaxCB
MaxCB

Reputation: 69

SQL Server query SUM from multiple tables

I came across an issue I cannot figure out unfortunately...

I have 2 tables: Purchase Orders Lines AND Sales Orders Lines. Now I need to pull info from a single PO AND also SUM of cases of a particular item (listed on that PO) FROM both Sales orders lines AND Purchase Orders lines. Like I am ordering 10 tables and I want to know that I already ordered 20 tables and I have sales orders for 25 tables. Below is my query.

SELECT s.POLID, s.ItemID, s.CSordered,
SUM(sl.CSopen) AS CSopenSO, SUM(pl.CSopen) AS CSopenPO
FROM PurchaseOrdersLines s

LEFT JOIN SalesOrdersLines sl ON s.ItemID = sl.ItemID
LEFT JOIN PurchaseOrdersLines pl ON s.ItemID = pl.ItemID

WHERE s.POID = '" . $row['POID'] . "'
GROUP BY s.POLID, s.ItemID, s.CSordered

I am getting SUM of CSopenSO correct but not SUM CSopenPO (it is 50 times higher than it should be). If I switch LEFT JOIN bringing Purchase Orders (pl) first then Sales Orders (sl) - then I get correct SUM of CSopenPO but not SUM of CSopenSO. I do not understand how the order of LEFT JOIN affects the sums and how to avoid it.

Thank you for your help in advance!!! Hope if it was clear..

*** Suggested by Jarlh

SELECT s.POLID, s.ItemID, s.CSordered, (
SELECT SUM(CSopen) FROM SalesOrdersLines sl WHERE sl.ItemID = s.ItemID
) AS CSopenSO, SUM(pl.CSopen) AS CSopenPO 
FROM PurchaseOrdersLines s
LEFT JOIN PurchaseOrdersLines pl ON s.ItemID = pl.ItemID
WHERE s.POID = '" . $row['POID'] . "'
GROUP BY s.POLID, s.ItemID, s.CSordered

However I still want to understand why my original query above is not working the way I want it to work. I would like to know what the error is.

Upvotes: 0

Views: 131

Answers (1)

Gordon Linoff
Gordon Linoff

Reputation: 1270773

Often, correlated subqueries are the most efficient method:

SELECT s.POLID, s.ItemID, s.CSordered,
       (SELECT SUM(sl.CSopen)
        FROM SalesOrdersLines sl 
        WHERE s.ItemID = sl.ItemID
       )  AS CSopenSO,
       (SELECT SUM(pl.CSopen)
        FROM PurchaseOrdersLines pl 
        WHERE s.ItemID = pl.ItemID
       ) AS CSopenPO 
FROM PurchaseOrdersLines s
WHERE s.POID = '" . $row['POID'] . "';

This assumes that the rows in s are not being combined.

Upvotes: 0

Related Questions