问题描述
如何在不支持此功能的DB2中实现LAG(COL1)over(按ID排序或按TMST ROWS进行未绑定的前缀和未绑定的跟随)。
我的意思是,我想基于LAG值派生一列(L_A_DATE),并且派生的列应继续具有先前的值,直到现有列不为空为止
ID COL1 STATUS A_DATE TMST
1 2020-08-08 OPEN NULL <current time>
1 2020-08-10 APPROVED 2020-08-09 <current time>
1 2020-08-13 OPEN NULL <current time>
1 2020-08-13 A_OPEN NULL <current time>
2 2020-08-08 OPEN NULL <current time>
2 2020-08-13 A_OPEN NULL <current time>
2 2020-08-15 APPROVED 2020-08-14 <current time>
2 2020-08-16 OPEN NULL <current time>
2 2020-08-16 W_OPEN NULL <current time>
2 2020-08-18 W_APPROVED 2020-08-17 <current time>
2 2020-08-19 OPEN NULL <current time>
2 2020-08-20 W_OPEN NULL <current time>
ID COL1 STATUS A_DATE L_A_DATE TMST
1 2020-08-08 OPEN NULL NULL <current time>
1 2020-08-10 APPROVED 2020-08-09 2020-08-09 <current time>
1 2020-08-13 OPEN NULL 2020-08-09 <current time>
1 2020-08-13 A_OPEN NULL 2020-08-09 <current time>
2 2020-08-08 OPEN NULL NULL <current time>
2 2020-08-13 A_OPEN NULL NULL <current time>
2 2020-08-15 APPROVED 2020-08-14 2020-08-14 <current time>
2 2020-08-16 OPEN NULL 2020-08-14 <current time>
2 2020-08-16 W_OPEN NULL 2020-08-14 <current time>
2 2020-08-18 W_APPROVED 2020-08-17 2020-08-17 <current time>
2 2020-08-19 OPEN NULL 2020-08-17 <current time>
2 2020-08-20 W_OPEN NULL 2020-08-17 <current time>
解决方法
您似乎想要最新的“已批准”值:
select t.*,max(case when status = 'Approved' then a_date end) over (partition by id order by col1) as l_a_date
from t;
或者,您可以使用累积max()
(这是您想要的另一种解释):
select t.*,max(a_date) over (partition by id
order by col1
rows between unbounded preceding and current row
) as l_a_date
from t;