我在下面的查询中有一个CTE,该CTE可以计算给定项目在过去45天内的销售量,并显示该项目销售的6周追踪平均值。
问题在于45天的计算和发货日期导致整个查询将所有数据相乘(此查询应产生1行vs 25行输出)。我确定发运日期和获取日期是CTE中引起查询乘法的代码行,但是由于我似乎正确地完成了所有操作,因此无法弄清楚如何解决该问题。
可以使用有关如何修改日期/获取日期字段的指南以正确显示数据。
我尝试注释掉以下几行代码,以更正该问题,因为此查询的输出应为一行,而不是几十行。
tl.shipdate (in select field)
tl.shipdate (in group by field)
where DATEDIFF(day, tl.shipdate, GETDATE() ) > 45
这是全部查询-我在上面为纠正查询而注释掉的行在ItemPurchased CTE中
With ItemMetrics As
(
select ilm.item_id,
ilm.REORDER_POINT ReorderPnt,
ilm.PREF_STOCK_LEVEL PrefStockLvl,
ilm.on_hand_count OnHandCnt,
ilm.on_order_count OnOrderCnt,
ilm.available_count AvailableCnt
from ns.ITEM_LOCATION_MAP ilm
where ilm.location_id = 3
),
ItemPurchased As
(
select sum(tl.unit_qty) TotalItemsBought, sum(tl.unit_qty)/6
SixWkAverage, i.item_id,tl.shipdate
from ns.tinvoice ti
join ns.transaction_lines tl on ti.transaction_id =
tl.transaction_id
join ns.items i on i.item_id = tl.item_id
where DATEDIFF(day, tl.shipdate, GETDATE() ) > 45
group by i.item_id,tl.shipdate
)
select tp.tranid, i.item_id, i.full_name,
i.displayname,sum(tl.item_count) -1 AmtOrdered, tl.location_id,
it_class.LIST_ITEM_NAME, tp.date_requested Due, v.printoncheckas
Vendor, tp.shipment_received ShipmntRecvd, IM.ReorderPnt,
IM.PrefStockLvl, IM.OnHandCnt, IM.OnOrderCnt,
IM.AvailableCnt,ipp.TotalItemsBought, ipp.SixWkAverage
from ns.tPurchaseOrder tp
inner join ns.Transaction_lines tl on tp.transaction_id =
tl.transaction_id
join ns.items i on i.item_id = tl.item_id
left join ns.ITEM_CLASSIFICATION it_class on it_class.list_id
= i.ITEM_CLASSIFICATION_ID
left join ns.vendors v on i.vendor_id = v.vendor_id
left join ns.dw_item_inventory_totals iit on i.item_id =
iit.item_id
left join ItemMetrics IM on im.item_id = i.item_id
left join ItemPurchased IPP on ipp.item_id = i.item_id
where tp.date_requested is not null and tp.location_id = 3
and tranid = '14980PO'
group by i.item_id, tp.date_requested, i.displayname,
tl.location_id, i.full_name, it_class.LIST_ITEM_NAME,
tp.item_id, v.printoncheckas, tp.tranid,
tp.shipment_received, IM.ReorderPnt, IM.PrefStockLvl,
IM.OnHandCnt, IM.OnOrderCnt, IM.AvailableCnt,
ipp.TotalItemsBought, ipp.SixWkAverage
答案 0 :(得分:0)
根据ZLK的评论,使用Max(tl.shipdate)并通过逐个语句从分组中删除shipdate,解决了该问题,因为在分组中有shipdate by导致每一行相乘。