sql查询生成如下输出

xtfmy6hx  于 2021-06-20  发布在  Mysql
关注(0)|答案(2)|浏览(318)

我必须想象预计的缺货项目和日期去库存。
我有一张表,上面写着这件商品什么时候会缺货。此表显示了一周中每周一的预计库存量。

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

这对我来说相当复杂。任何帮助都将不胜感激。
你好,普拉杰沃尔

g6ll5ycj

g6ll5ycj1#

试试这个:

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
efzxgjgh

efzxgjgh2#

您可以使用(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演示
它将为每个组选择第一个低于20的值,该组由低于20的项目/位置/条纹组成。

相关问题