我有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;
答案 0 :(得分: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
答案 1 :(得分: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没有匹配记录(即该墨水代码没有墨水交付),那么这些行的值将为空。
如果您不能假设墨水只能在收到墨水后才能送出,那么您还需要链接到墨水表(即墨水代码为主键的表格),或者联合全部接收和交付表中的墨水代码,并链接到:
;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