我在下面的查询中有一个CTE,它应该计算给定项目在过去45天内的销售金额,并显示该项目6周的销售往绩平均值。
问题是45天的计算和发货日期导致整个查询乘以所有数据(此查询应产生1行与25行的输出)。我发现shipdate和get date是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
发布于 2019-01-11 00:39:37
根据ZLK的评论,使用Max(tl.shipdate)并从group by语句中删除shipdate解决了这个问题,因为在group by中使用shipdate会导致每一行相乘。
https://stackoverflow.com/questions/54138752
复制相似问题