我差不多2年前发布了以下问题并得到了一个完美的答案,但现在我需要扩展这个问题以获得缺货持续时间。这是我提供的原始问题和答案:
"我需要确定库存库存和缺货的模式。
我有一张表格,显示项目,位置,库存和日期。我想知道一个项目/位置缺货的情况是否存在时间模式。该文件包含滚动三周的数据。如果一件物品在三周内持续不稳定或缺货,那么我需要了解它以进一步研究。
如果库存大于零,则项目/位置是instock。如果库存为零或为负,则物料/库位缺货。
感谢您的帮助。
示例数据
Item, location, inventory, date
1243, 10, 2, 3/12/2012
1243, 10, 0, 3/13/2012
1243, 10, -2, 3/14/2012
1243, 10, -2, 3/15/2012
1243, 10, 4, 3/16/2012
然后添加项目,位置,库存,日期记录。 "
我收到了这个答案,效果很好。
SELECT item,
location,
SUM( CASE WHEN status = 'In Stock' AND prior_status = 'Out of Stock'
THEN 1
ELSE 0
END) moved_to_out_of_stock,
SUM( CASE WHEN status = 'Out of Stock' AND prior_status = 'In Stock'
THEN 1
ELSE 0
END) moved_to_in_stock
FROM (SELECT item,
location,
status,
lag( status ) over (partition by item, location
order by dt) prior_status
FROM (SELECT item,
location,
(case when inventory <= 0
then 'Out of Stock'
else 'In Stock'
end) status,
dt
FROM your_table))
GROUP BY item, location
现在我希望能够确定“缺货”的持续时间。每次发生。基本上这个项目有多少天,每次缺货时都会缺货。
非常感谢任何帮助。
EDIT 这是我目前使用的查询:
select ari.ITEM, x.LOCATION, MOVED_TO_OUT_OF_STOCK, MOVED_TO_IN_STOCK
from (select item, location,
SUM(CASE WHEN status = 'In Stock' AND prior_status = 'Out of Stock'
THEN 1
ELSE 0
END)
moved_to_out_of_stock,
SUM(CASE WHEN status = 'Out of Stock' AND prior_status = 'In Stock'
THEN 1
ELSE 0
END)
moved_to_in_stock
FROM (select item, location, status, lag(status)
over (partition by item, location
order by repl_date) prior_status
FROM (select item, location,(CASE WHEN (stock_on_hand - demo_stock - non_sellable_qty) <='0'--subtract demo stock and non sellable qty
then 'Out of Stock'
else 'In Stock'
end)
status, repl_date
from repl_results))
group by item, location) x, active_repl_items ari,
(select item, location, min(repl_date) as min_repl_date from repl_results
group by item, location)y,
(select item, location, repl_date, (STOCK_ON_HAND-DEMO_STOCK-NON_SELLABLE_QTY) AS NET_AVAIL from repl_results) z
where (x.item = ari.item or x.item = ari.primary_pack_no) --to account for pack_items
and x.item = y.item and x.item = z.item
and x.location = y.location and x.location = z.location
and y.min_repl_date = z.repl_date
and x.location = ari.location
答案 0 :(得分:0)
以下是解决问题的方法。每次发现缺货情况时添加0/1标志。然后做这个标志的累积总和。该累计金额按顺序识别缺货情况。当您按此累计金额汇总时,您可以获得缺货情况的持续时间:
select item, location, ooi_grp, min(dt) as mindt, max(dt) as maxdt,
(max(dt) - min(dt) + 1) as duration
from (select t.*, sum(startooi_flag) over (partition by item, location order by dt) as ooi_grp
FROM (SELECT item, location, status,
(case when lag(inventory) over (partition by item, location order by dt) > 0 and
inventory <= 0
then 1 else 0
end) as startooi_flag
FROM your_table
) t
) t
where inventory <= 0
group by item, location;