I have two tables, SHPORD and CUSTORD, and I want to get the sum of uncompleted units for all orders that have not yet been fulfilled through today. Example at bottom.
Separate queries look like this:
SELECT SHPORD.ITEM, SUM(ISNULL(SHPORD.QTY_OPEN,0)) AS SHPSUM
FROM SHPORD SHPORD
WHERE SHPORD.DATE_DUE <= GETDATE() AND SHPORD.QTY_OPEN > 0
GROUP BY SHPORD.ITEM
SELECT CUSTORD.ITEM, SUM(ISNULL(CUSTORD.QTY_OPEN,0)) AS CUSTSUM
FROM CUSTORD CUSTORD
WHERE CUSTORD.DATE_DUE <= GETDATE() AND CUSTORD.QTY_OPEN > 0
GROUP BY CUSTORD.ITEM
These return the desired results.
But if I try to combine them like so:
SELECT CUSTORD.ITEM, SUM(ISNULL(CUSTORD.QTY_OPEN,0)) AS CUSTSUM, SUM(ISNULL(SHPORD.QTY_OPEN,0)) AS SHPSUM
FROM CUSTORD CUSTORD
LEFT JOIN SHPORD SHPORD ON CUSTORD.ITEM = SHPORD.ITEM
AND SHPORD.DATE_DUE <= GETDATE() AND SHPORD.QTY_OPEN > 0
WHERE CUSTORD.DATE_DUE <= GETDATE() AND CUSTORD.QTY_OPEN > 0
GROUP BY CUSTORD.ITEM
I get the wrong results for about a third of the items.
This query has been deconstructed to be as simple as possible and the issue only occurs when both SUM columns are used. I'm at a loss. Probably just missing something simple.
What query should I be using?
Examples:
Table CUSTORD
CO# ITEM QTY OPEN
111 A 5
222 B 10
333 A 15
Table SHPORD
SO# ITEM QTY OPEN
444 B 2
555 B 4
666 A 7
OUPUT
ITEM CUSTSUM SHPSUM
A 20 6
B 10 7