我有三个表:零件数据,订单数据和发货数据。 尝试编写存储过程,返回部件号,名称等以及仍要装运的部件数量。
当某些订单中的某些零件已经发货时 - 我们必须从订单中订购的零件总数中减去该数量。 如果尚未发出特定订单的零件 - 我们必须显示订购零件的数量。
我到目前为止尝试过:
PROCEDURE dbo.GetParts
AS
SELECT od.OrderDetailID, od.PartNr, od.OrderNr, d.PartName, RemainsToBeShipped =
CASE
WHEN EXISTS(SELECT sh.Quantity FROM Shipped AS sh WHERE sh.OrderDetailID = od.OrderDetailID)
THEN od.Quantity - sh.Quantity
ELSE od.Quantity
END
FROM OrderDetails AS od, Parts AS d, Shipped as s
WHERE od.NrDet = d.NrDet AND od.OrderDetailID = s.OrderDetailID
这不起作用 - “ELSE”永远不会发射之后的部分。
答案 0 :(得分:1)
SELECT
od.OrderDetailID, od.PartNr, od.OrderNr, d.PartName
, od.Quantity - ISNULL(s.Quantity,0) [RemainsToBeShipped]
FROM OrderDetails AS od
INNER JOIN Parts AS d ON od.NrDet = d.NrDet
LEFT JOIN Shipped as s ON od.OrderDetailID = s.OrderDetailID
答案 1 :(得分:0)
您的加入会阻止您获取任何未发货的物品。试试这个:
SELECT od.OrderDetailID, od.PartNr, od.OrderNr, d.PartName, RemainsToBeShipped =
od.Quantity - ISNULL(s.Quantity,0)
FROM OrderDetails AS od
INNER JOIN Parts AS d ON od.NrDet = d.NrDet
LEFT OUTER JOIN Shipped AS s ON od.OrderDetailID = s.OrderDetailID