I have to visualize Projected Out of Stock Items and the date it goes out of stock in the inventory.
I have a table which shows when the item may go out of stock. This table shows the Projected Inventory for every Monday of the week.
Item Location Projected Inventory Date
A1 L1 0 Aug 20, 2018
A1 L1 0 August 27, 2018
A1 L1 54 Sep 03,20-18
A1 L1 49 Sep 10, 2018
A1 L1 44 Sep 17
A1 L1 39 Sep 24
A1 L1 32 Oct 1
A1 L1 25 Oct 8
A1 L1 18 Oct 15
A1 L1 12 Oct 22
A1 L1 5 Oct 29
A1 L1 55 Nov 5
A1 L1 45 Nov 12
An item is considered to be Out of Stock if the : Projected Invenotry<20
. Since the data is for every Monday of the week, it may take few weeks for the item to come back on stock(ie PI > 20
).
As can be seen in the table, Item A1 goes out of stock on Aug 20, 2018 and comes back on stock on Sep 03, 2018. The output table desired is :
Item Location PI Date Out of Stock
A1 L1 0 Aug 20, 2018
A1 L1 18 Oct 15, 2018
This is quite complex for me. Any help would be greatly appreciated.
Regards, Prajwal
You could use (MySQL 8.0+):
WITH cte AS (
SELECT *, SUM(CASE WHEN Projected < 20 THEN 0 ELSE 1 END)
OVER(PARTITION BY Item, Location ORDER BY Inventory_Date) AS subgrp
FROM tab
), cte2 AS (
SELECT *, ROW_NUMBER()
OVER(PARTITION BY Item, Location, subgrp ORDER BY Inventory_Date) AS rn
FROM cte
)
SELECT *
FROM cte2
WHERE (Item, Location, subgrp,rn) IN (SELECT Item, Location, subgrp, MIN(rn)
FROM cte2 c
WHERE Projected < 20
GROUP BY Item, Location, subgrp)
ORDER BY Inventory_Date;
It will select first value below 20 per group that consists of Item/Location/Streak_of_values_below_20.
Try this:
select @lag := 0;
select item, location, projected, `date` from (
select @lag projectedLag, @lag:=projected,
item, location, projected, `date`
from tab
order by `date`
) a where projectedLag >= 20 and projected < 20
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.