我有一个老化查询,它以 12、24 和 36 个月为间隔对购买的物品数量及其成本进行老化。查询运行得很好,但是与用于查找特定供应商总数的单个查询相比,我的总数不会相加。
见下文。
SELECT s.SupplierNumber as Supplier_Number
, s.suppliername as Supplier_Name
, i.supplierpartnum as Part_No
, SUBSTRING(e.account_code,1,5)/*+'-'+RIGHT(e.account_code,7)*/ as Account_Code
, CASE WHEN e.reference_code = ''
THEN 'NOREF'
ELSE reference_code
END as Reference_Code
, i.Commodity
, i.ShortDscrptn as Part_Desc
, i.unitofmeasure as UOM
, i.unitprice as Unit_Price
, CASE WHEN h.OrderDate >= '2012-01-01'
AND h.OrderDate <= '2012-12-31'
THEN COUNT(i.Quantity)
ELSE 0 END as Annual_Qty_12
, CASE WHEN h.OrderDate >= '2011-01-01'
AND h.OrderDate <= '2012-12-31'
THEN COUNT(i.Quantity)
ELSE 0 END as Annual_Qty_24
, CASE WHEN h.OrderDate >= '2010-01-01'
AND h.OrderDate <= '2012-12-31'
THEN COUNT(i.Quantity)
ELSE 0 END as Annual_Qty_36
, CASE WHEN h.OrderDate >= '2012-01-01'
AND h.OrderDate <= '2012-12-31'
THEN SUM(i.UnitPrice)
ELSE 0 END as Annual_Spend_12
, CASE WHEN h.OrderDate >= '2011-01-01'
AND h.OrderDate <= '2012-12-31'
THEN SUM(i.UnitPrice)
ELSE 0 END as Annual_Spend_24
, CASE WHEN h.OrderDate >= '2010-01-01'
AND h.OrderDate <= '2012-12-31'
THEN SUM(i.UnitPrice)
ELSE 0 END as Annual_Spend_36
FROM ekp.dbo.SUPPLIER s
JOIN ekp.dbo.ORDERHEADER h
ON s.SupplierID = h.SupplierID
JOIN ekp.dbo.ORDERITEM i
ON h.OrderID = i.OrderID
JOIN mgnt.dbo.ematch e
ON h.PONumber = e.po_ctrl_num
AND i.LineNumber = e.po_sequence_id
WHERE h.OrderDate >= '2010-01-01'
AND h.OrderDate <= '2012-12-31'
GROUP BY s.SupplierNumber, s.SupplierName, i.SupplierPartNum, e.account_code
, i.Commodity, i.UnitOfMeasure, i.UnitPrice, i.ShortDscrptn, h.OrderDate
, e.reference_code
我可以继续将结果复制到电子表格中,并对Annual_Spend_12
特定的列求和Supplier
,但它与以下内容不匹配:
SELECT SUM(i.unitprice) as Annual_Spend_12
FROM ekp.dbo.ORDERITEM i
JOIN ekp.dbo.ORDERHEADER h
ON i.OrderID = h.OrderID
JOIN ekp.dbo.Supplier s
ON h.SupplierID = s.SupplierID
JOIN mgnt.dbo.ematch e
ON h.PONumber = e.po_ctrl_num
AND i.LineNumber = e.po_sequence_id
WHERE s.SupplierNumber = '15302'
AND h.OrderDate >= '2012-01-01'
AND h.OrderDate <= '2012-12-31'
上面这个查询的总和总是比顶部查询高得多。我还对整个聚合进行了求和和计数,但它也不匹配,实际上,它产生的结果与顶部查询相同:
, COUNT(CASE WHEN h.OrderDate >= '2012-01-01'
AND h.OrderDate <= '2012-12-31'
THEN i.Quantity
ELSE 0 END) as Annual_Qty_12
, COUNT(CASE WHEN h.OrderDate >= '2011-01-01'
AND h.OrderDate <= '2012-12-31'
THEN i.Quantity
ELSE 0 END) as Annual_Qty_24
, COUNT(CASE WHEN h.OrderDate >= '2010-01-01'
AND h.OrderDate <= '2012-12-31'
THEN i.Quantity
ELSE 0 END) as Annual_Qty_36
, SUM(CASE WHEN h.OrderDate >= '2012-01-01'
AND h.OrderDate <= '2012-12-31'
THEN i.UnitPrice
ELSE 0 END) as Annual_Spend_12
, SUM(CASE WHEN h.OrderDate >= '2011-01-01'
AND h.OrderDate <= '2012-12-31'
THEN i.UnitPrice
ELSE 0 END) as Annual_Spend_24
, SUM(CASE WHEN h.OrderDate >= '2010-01-01'
AND h.OrderDate <= '2012-12-31'
THEN i.UnitPrice
ELSE 0 END) as Annual_Spend_36
我非常害怕为每个聚合编写一个带有临时表的存储过程。
任何帮助表示赞赏。