1

我正在尝试使用以下 sql 来检索收到的总金额,以及从 3 个表中售出的总金额:

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

上面的查询返回的数据比实际值大几个数量级。但是,如果我将其分为两个查询:

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

它完美地工作。是什么赋予了?连接所有三个表的第一个查询是否有任何原因不起作用,但两个单独的查询会?

4

1 回答 1

7

If either receivings or sales has 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:

select ITEMS.ITEM_NO, COALESCE(R.SUM_RECEIVINGS,0), COALESCE(S.SUM_SALES,0)
from ITEMS
left join (SELECT RECEIVINGS.ITEM_NO, SUM(RECEIVINGS.QTY_RECVD) as SUM_RECEIVINGS
    FROM RECEIVINGS
    GROUP BY RECEIVINGS.ITEM_NO) as R ON ITEMS.ITEM_NO = R.ITEM_NO
left join (SELECT SALES.ITEM_NO, SUM(SALES.QTY_RECVD) as SUM_SALES
    FROM SALES
    GROUP BY SALES.ITEM_NO) as S ON ITEMS.ITEM_NO = S.ITEM_NO
WHERE ITEMS.ITEM_NO = '12345'
于 2012-04-09T15:00:01.923 回答