3

2张桌子我有 2 个表 Tblinkreceiving 和 Tblinkdelivery。我想显示每个墨水代码的库存余额。我尝试了下面的 sql 连接查询,但是当我交叉检查手动计算时,许多墨水代码的计算是错误的。哪里出错了?

select r.inkcode, SUM(r.quantity) Stock-In, SUM(d.quantity) Stock-out, (SUM(r.quantity) - SUM(d.quantity)) Stock-Balance from Tblinkreceiving r,Tblinkdelivery d where r.inkcode=d.inkcode
group by r.inkcode;
4

2 回答 2

0

您已使用内部连接(隐式)来组合接收和交付。这意味着任何已收到但未交付的墨水代码都将从您的结果中排除。

如果您可以假设对于任何墨水交付都必须有墨水收据(基于您无法交付尚未收到的东西的前提),那么您可以在 tblInkReceiving 上使用内部连接,如下所示:

SELECT r.inkcode, 
    SUM(r.quantity) AS Stock-In, 
    ISNULL(SUM(d.quantity), 0) AS Stock-out,
    SUM(r.quantity) - ISNULL(SUM(d.quantity), 0) AS Stock-Balance 
FROM Tblinkreceiving r LEFT JOIN Tblinkdelivery d ON r.inkcode = d.inkcode
GROUP BY r.inkcode

左连接将返回左侧 (r) 上的所有记录,包括右侧 (d) 上的匹配记录。如果 d 没有匹配的记录(即该墨水代码没有墨水交付),那么这些行的值将为空。

如果您不能假设墨水只有在收到后才能交付,那么您也需要链接到墨水表(即,以 inkcode 为主键的表),或者合并所有墨水代码在接收和交付表中,并链接到:

;WITH cte AS (SELECT inkcode FROM Tblinkreceiving 
    UNION 
    SELECT inkcode FROM Tblinkdelivery)
SELECT cte.inkcode, 
    SUM(r.quantity) AS Stock-In, 
    ISNULL(SUM(d.quantity), 0) AS Stock-out,
    SUM(r.quantity) - ISNULL(SUM(d.quantity), 0) AS Stock-Balance 
FROM cte LEFT JOIN Tblinkreceiving r ON cte.ink_code = r.ink_code
    LEFT JOIN Tblinkdelivery d ON cte.inkcode = d.inkcode
GROUP BY cte.inkcode
于 2012-04-24T09:27:57.177 回答
0
WITH    i AS
        (
        SELECT  inkcode, SUM(quantity) AS qin
        FROM    tblInkReceiving
        GROUP BY
                inkcode
        ),
        o AS
        (
        SELECT  inkcode, SUM(quantity) AS qout
        FROM    tblInkDelivery
        GROUP BY
                inkcode
        )
SELECT  COALESCE(i.inkcode, o.inkcode) AS inkcode,
        COALESCE(qin, 0) AS stock_in,
        COALESCE(qout, 0) AS stock_out,
        COALESCE(qin, 0) - COALESCE(qout, 0) AS stock_balance
FROM    i
FULL JOIN
        o
ON      o.inkcode = i.inkcode
于 2012-04-24T08:42:09.993 回答