3路SQL加入返回错误数据

时间:2012-04-09 14:54:44

标签: sql tsql join

我正在尝试使用以下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

它完美无缺。是什么赋予了?有没有理由加入所有三个表的第一个查询不起作用,但是两个单独的查询会不会?

1 个答案:

答案 0 :(得分:7)

如果receivingssales有多行(特别是如果两行都有多行),则每个值都会乘以另一行中的行数。解决此问题的一种方法是分别计算总数,然后加入:

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'