我正在尝试创建一个查询,以将每个商店的前20个缺货SKU下拉。这是我到目前为止的内容:
;with top20OOS as
(select wi.SKU
, count(wi.SKU) OOSCount
, wi.ProductId
, wi.PseudoStoreId
from WaveItem wi (nolock)
where wi.isOutOfStock = 1
and DateAdded between '2018-01-01' and '2018-05-31'
group by wi.SKU, p.ProductName, wi.ProductId, bo.brandname, p.size, mo.name,
wi.PseudoStoreId
)
select oos.SKU
, oos.ProductName
, oos.OOSCount
, s.StoreName
, s.StoreID from top20OOS oos
join WaveItem wi (nolock) on wi.ProductId = oos.ProductId
and wi.PseudoStoreId = oos.PseudoStoreId
join tblStore s (nolock) on s.PseudoStoreID = wi.PseudoStoreId
where s.StoreID in (1094,1088)
and DateAdded between '2018-01-01' and '2018-05-31'
group by oos.SKU, oos.ProductName, s.StoreName, s.StoreID, oos.OOSCount
order by s.StoreName asc, OOSCount desc
这只会拉出1094和1088商店的所有缺货SKU,我需要将其限制为每个商店的前20名。我正在使用SQL Server 2017
答案 0 :(得分:0)
这有点冗长,因为我不记得ROW_NUMBER()是否在同一查询中与Group By配合良好,所以我谨慎行事并将其分解为单独的子查询。
;with top20OOS as
(select wi.SKU
, count(wi.SKU) OOSCount
, wi.ProductId
, wi.PseudoStoreId
from WaveItem wi (nolock)
where wi.isOutOfStock = 1
and DateAdded between '2018-01-01' and '2018-05-31'
group by wi.SKU, p.ProductName, wi.ProductId, bo.brandname, p.size, mo.name,
wi.PseudoStoreId
)
SELECT sku,
productName,
OOSCount,
StoreName,
StoreID
FROM (SELECT sku,
productName,
OOSCount,
StoreName,
StoreID,
ROW_NUMBER() OVER
( PARTITION BY StoreID
ORDER BY OOSCount
) AS rn
FROM (select oos.SKU
, oos.ProductName
, oos.OOSCount
, s.StoreName
, s.StoreID from top20OOS oos
join WaveItem wi (nolock) on wi.ProductId = oos.ProductId
and wi.PseudoStoreId = oos.PseudoStoreId
join tblStore s (nolock) on s.PseudoStoreID = wi.PseudoStoreId
where s.StoreID in (1094,1088)
and DateAdded between '2018-01-01' and '2018-05-31'
group by oos.SKU, oos.ProductName, s.StoreName, s.StoreID, oos.OOSCount
) TMP
) TMP2
WHERE rn <= 20;