我有下表结果。
条件:
按CUSTID和ITEMID进行分区 其中end_dt不为null 如果RESP列为空,则获取具有条目的最新值。
CUSTID ITEMID START_DT END_DT RESP START_CYCLE END_CYCLE
1 101 1/1/2019 4/1/2019 400 1/1/2019 1/12/2019
1 101 1/1/2019 4/1/2019 1/13/2019 1/18/2019
1 101 1/1/2019 4/1/2019 750 1/19/2019 2/15/2019
1 101 1/1/2019 4/1/2019 2/16/2019 4/1/2019
2 909 3/1/2019 444 3/1/2019 3/2/2019
2 909 3/1/2019 3/3/2019 3/10/2019
2 909 3/1/2019 767 3/11/2019 3/28/2019
2 909 3/1/2019 3/29/2019 12/31/3000
预期结果:
CUSTID ITEMID START_DT END_DT RESP START_CYCLE END_CYCLE
1 101 1/1/2019 4/1/2019 400 1/1/2019 1/12/2019
1 101 1/1/2019 4/1/2019 1/13/2019 1/18/2019
1 101 1/1/2019 4/1/2019 750 1/19/2019 2/15/2019
1 101 1/1/2019 4/1/2019 750 2/16/2019 4/1/2019
2 909 3/1/2019 444 3/1/2019 3/2/2019
2 909 3/1/2019 3/3/2019 3/10/2019
2 909 3/1/2019 767 3/11/2019 3/28/2019
2 909 3/1/2019 3/29/2019 12/31/3000
唯一更改的行是
1 101 1/1/2019 4/1/2019 750 2/16/2019 4/1/2019
此行不应更改,这是正确的:
1 101 1/1/2019 4/1/2019 1/13/2019 1/18/2019
答案 0 :(得分:1)
您必须检查三件事:resp为null,end_dt不为null,以及如果这是此客户监督项id的最后一行。仅在这种情况下,请使用last_value,例如此处的resp2
列:
select custid, itemid, start_dt, end_dt, resp, start_cycle, end_cycle,
case when resp is null
and end_dt is not null
and lead(itemid) over (partition by custid, itemid order by start_cycle) is null
then last_value(resp) ignore nulls
over (partition by custid, itemid order by start_cycle)
else resp
end resp2
from t