我在我的多个表的查询中有一个总和列“Sum(Material_Location.On_Hand_Qty)Stock”,我已经将它们连接在一起。但是,如果没有库存或零数量,则查询中不会显示任何行或数据。我怎样才能让行或数据显示为零数量?坚持请帮助。
SELECT (Material_Location.Material) Part, Material.Description,
SUM(Material_Location.On_Hand_Qty) Stock,
(Material.Order_Point)MinTarget, (Material.Stocked_UofM)Unit,
(Job.In_Production_Quantity)InProductionQty,
Material.Class, (SO_Detail.Order_Qty)OnOrderQty
FROM PRODUCTION.dbo.Material Material,
PRODUCTION.dbo.Material_Location Material_Location
LEFT JOIN (SELECT Job.Part_Number, Sum(In_Production_Quantity) In_Production_Quantity
FROM PRODUCTION.dbo.Job Job
Where Job.Status = 'Active'
Group by Job.Part_Number
)Job on Job.Part_Number = Material_Location.Material
LEFT JOIN (SELECT SO_Detail.Material, Sum(Order_Qty) Order_Qty
FROM PRODUCTION.dbo.SO_Detail SO_Detail
Where SO_Detail.Status = 'Open'
Group by SO_Detail.Material
)SO_Detail on SO_Detail.Material = Material_Location.Material
WHERE Material.Material = Material_Location.Material
AND Material.Material In ('xxxxxx', 'xxxxx')
GROUP BY Material_Location.Material, Material.Description,
Material.Order_Point, Material.Stocked_UofM,
Job.In_Production_Quantity, Material.Class,
SO_Detail.Order_Qty
答案 0 :(得分:0)
我认为问题在于您正在对正在进行INNER JOIN的_Material_Location_表中的值求和(即,您使用逗号使用了旧的连接语法)。
将其更改为LEFT OUTER JOIN应解决该问题: -
SELECT Material_Location.Material AS Part,
Material.Description,
Material.Order_Point AS MinTarget,
Material.Stocked_UofM AS Unit,
Job.In_Production_Quantity AS InProductionQty,
Material.Class,
SO_Detail.Order_Qty AS OnOrderQty,
SUM(Material_Location.On_Hand_Qty AS Stock
FROM PRODUCTION.dbo.Material Material
LEFT OUTER JOIN PRODUCTION.dbo.Material_Location Material_Location ON Material.Material = Material_Location.Material
LEFT OUTER JOIN
(
SELECT Job.Part_Number,
Sum(In_Production_Quantity) In_Production_Quantity
FROM PRODUCTION.dbo.Job Job
WHERE Job.Status = 'Active'
GROUP BY Job.Part_Number
)Job ON Job.Part_Number = Material_Location.Material
LEFT OUTER JOIN
(
SELECT SO_Detail.Material,
SUM(Order_Qty) Order_Qty
FROM PRODUCTION.dbo.SO_Detail SO_Detail
WHERE SO_Detail.Status = 'Open'
GROUP BY SO_Detail.Material
)SO_Detail on SO_Detail.Material = Material_Location.Material
WHERE Material.Material In ('xxxxxx', 'xxxxx')
GROUP BY Material_Location.Material,
Material.Description,
Material.Order_Point,
Material.Stocked_UofM,
Job.In_Production_Quantity,
Material.Class,
SO_Detail.Order_Qty
请注意,将旧样式隐式连接语法与较新的显式连接语法混合通常是一个坏主意。由于不同类型的连接之间的优先级不同,可能会出现奇怪的问题。