SQL查询产生如下所示的输出

时间:2018-08-24 15:01:40

标签: mysql

我必须可视化“预计缺货”项目及其在库存中缺货的日期。

我有一张桌子,显示什么时候该物品可能缺货。该表显示一周中每个星期一的预计库存。

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

如果有Projected Invenotry<20,则该商品被视为缺货。由于数据是一周中的每个星期一的数据,因此该项目可能要花几周的时间才能重新库存(即PI > 20)。

从表中可以看出,物料A1于2018年8月20日断货,并于2018年9月3日恢复库存。所需的输出表是:

Item    Location    PI    Date Out of Stock
A1       L1         0       Aug 20, 2018
A1       L1         18      Oct 15, 2018

这对我来说很复杂。任何帮助将不胜感激。

关于, 普赖瓦尔

2 个答案:

答案 0 :(得分:0)

您可以使用(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;

DBFiddle Demo

它将选择每组20以下的第一个值,该值由Item / Location / Streak_of_values_below_20组成。

答案 1 :(得分:0)

尝试一下:

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