这个问题已经得到回答,但我无法得到查询的几个部分。下面是输入表。
ID NAME DISEASE DRUG SHIP_DATE SUPPLY
1 aa D1 dd 10-05-2020 30
1 aa D1 dd 07-06-2020 30
1 aa D1 dd 12-07-2020 30
1 aa D1 dd 09-08-2020 30
1 aa D1 dd 07-09-2020 28
1 aa D1 dd 11-10-2020 28
1 aa D1 dd 10-11-2020 28
2 bb D2 cd 01-01-2020 10
2 bb D2 cd 06-01-2020 10
我的要求是获得下一个订单(发货日期)是早还是晚。例如- 第一个订单是在 10-05-2020 + 供应(30)= 09-06-2020(下一个预期日期),但患者在 2020 年 7 月 6 日订购,所以第二个订单是早期订单案例。现在,07-06-2020+supply(30)= 09-07-2020(预计日期),但患者于 2020 年 7 月 12 日订购。第三个订单是延迟订单案例。
如果订单较早,则下一个预期日期为发货日期 +供应,但如果订单较晚,则下一个预期日期为上一个预期日期 + 供应。(操作会更好地理解)
ID NAME DISEASE DRUG SHIP_DATE SUPPLY EXP_DATE LATE_OR_EARLY GAP
-- ---- ------- ---- ---------- ---------- ---------- ------------- ---
1 aa D1 dd 10-05-2020 30 first order
1 aa D1 dd 07-06-2020 30 09-06-2020 early
1 aa D1 dd 12-07-2020 30 09-07-2020 late 3
1 aa D1 dd 09-08-2020 30 11-08-2020 early
1 aa D1 dd 07-09-2020 28 10-09-2020 early
1 aa D1 dd 11-10-2020 28 08-10-2020 late 3
1 aa D1 dd 10-11-2020 28 08-11-2020 late 2
2 bb D2 cd 01-01-2020 10 first order
2 bb D2 cd 06-01-2020 10 11-01-2020 early
下面是我从 Stack Overflow 得到的查询:
1. with prep (id, name, disease, drug, ship_date, supply, e_date,
cls, exp_date) as (
select id, name, disease, drug, ship_date, supply, e_date, cls,
case cls when 'A' then lag(e_date + supply)
over (partition by id, disease, drug
order by ship_date)
else e_date end as exp_date
from input_table
match_recognize(
partition by id, disease, drug
order by ship_date
measures a.ship_date + sum(supply) - supply as e_date,
classifier() as cls
all rows per match
pattern (a b*)
define b as ship_date <= a.ship_date + sum(supply) - supply
) ) select id, name, disease, drug, ship_date, supply, exp_date,
case when exp_date is null then 'first order'
when cls = 'A' then 'late'
else 'early' end as late_or_early,
case cls when 'A' then ship_date - exp_date end as gap from prep order by id, disease, drug, ship_date ;
模式和定义子句实际上在这里做什么以及它如何计算所需的结果?