我试着编写一个脚本来返回同一个字段上的4个不同的计算,但我真的希望结果返回一行。
当有结果时,它会为每个结果返回一个新行。
SELECT DISTINCT
sp.PartNumber,
(StandardUnitMaterialCost+StandardUnitRunCost+StandardUnitSetCost+StandardUnitSubcontractCost+StandardLandedCost1+StandardLandedCost2+StandardLandedCost3+StandardLandedCost4+StandardLandedCost5)
,
(select ISNULL(sum(quantity),0) from stores.StockLogPart where month(TransactionDate) < MONTH(getdate()) AND year(TransactionDate) <= year(getdate()) AND slp.PartID = Stores.StockLogPart.PartID)
,
(select ISNULL(sum(quantity),0) from stores.StockLogPart where month(TransactionDate) = MONTH(getdate()) AND year(TransactionDate) <= year(getdate()) AND slp.PartID = Stores.StockLogPart.PartID)
,
(select ISNULL(sum(quantity),0) from stores.StockLogPart where month(TransactionDate) = MONTH(getdate()) AND year(TransactionDate) <= year(getdate()) AND slp.TransactionCodeID IN (1,2,13) AND slp.PartID = Stores.StockLogPart.PartID)
,
(select ISNULL(sum(quantity),0) from stores.StockLogPart where month(TransactionDate) = MONTH(getdate()) AND year(TransactionDate) <= year(getdate()) AND slp.TransactionCodeID IN (3,7) AND slp.PartID = Stores.StockLogPart.PartID)
FROM Stores.StockLogPart slp
JOIN Structure.Parts sp ON sp.PartID = slp.PartID
JOIN Stores.ProductGroups pg ON pg.ProductGroupID = sp.ProductGroupID
WHERE pg.ProductGroupCode = 'XX'
答案 0 :(得分:1)
我认为你需要删除一个连接。这有点困难,因为它不清楚哪些表格中的成本字段。试试这个:
SELECT DISTINCT
sp.PartNumber,
(StandardUnitMaterialCost+StandardUnitRunCost+StandardUnitSetCost+StandardUnitSubcontractCost+StandardLandedCost1+StandardLandedCost2+StandardLandedCost3+StandardLandedCost4+StandardLandedCost5)
,
(select ISNULL(sum(quantity),0) from stores.StockLogPart where month(TransactionDate) < MONTH(getdate()) AND year(TransactionDate) <= year(getdate()) AND sp.PartID = Stores.StockLogPart.PartID)
,
(select ISNULL(sum(quantity),0) from stores.StockLogPart where month(TransactionDate) = MONTH(getdate()) AND year(TransactionDate) <= year(getdate()) AND sp.PartID = Stores.StockLogPart.PartID)
,
(select ISNULL(sum(quantity),0) from stores.StockLogPart where month(TransactionDate) = MONTH(getdate()) AND year(TransactionDate) <= year(getdate()) AND stores.StockLogPart.TransactionCodeID IN (1,2,13) AND sp.PartID = Stores.StockLogPart.PartID)
,
(select ISNULL(sum(quantity),0) from stores.StockLogPart where month(TransactionDate) = MONTH(getdate()) AND year(TransactionDate) <= year(getdate()) AND stores.StockLogPart.TransactionCodeID IN (3,7) AND sp.PartID = Stores.StockLogPart.PartID)
FROM Structure.Parts sp
JOIN Stores.ProductGroups pg ON pg.ProductGroupID = sp.ProductGroupID
WHERE pg.ProductGroupCode = 'XX'