I’m attempting to use the following sql to retrieve the total amount received, and the total amount sold from 3 tables:
select ITEMS.ITEM_NO, SUM(RECEIVINGS.QTY_RECVD), SUM(SALES.QTY_SOLD)
from ITEMS
left join RECEIVINGS
on ITEMS.ITEM_NO = RECEVINGS.ITEM_NO
left join SALES
on ITEMS.ITEM_NO = SALES.ITEM_NO
WHERE ITEMS.ITEM_NO = '12345'
GROUP BY ITEMS.ITEM_NO
The query above returns data that is several orders of magnitude greater than the actual values. However, if I break it into two queries:
select ITEMS.ITEM_NO, SUM(RECEIVINGS.QTY_RECVD)
from ITEMS
left join RECEIVINGS
on ITEMS.ITEM_NO = RECEVINGS.ITEM_NO
WHERE ITEMS.ITEM_NO = '12345'
GROUP BY ITEMS.ITEM_NO
select ITEMS.ITEM_NO, SUM(SALES.QTY_SOLD)
from ITEMS
left join SALES
on ITEMS.ITEM_NO = SALES.ITEM_NO
WHERE ITEMS.ITEM_NO = '12345'
GROUP BY ITEMS.ITEM_NO
it works perfectly. What gives? Is there any reason the first query that joins all three tables won’t work, yet two separate queries will?
If either
receivingsorsaleshas more than one row (and especially if both have more than one row) then the values will each get multiplied by the number of rows in the other. One way to solve this issue is to calculate the totals separately then join: