如何解决DB2:实施LAG ROWS无限制的执行和无限制的遵循
如何在不支持此功能的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>
DB2数据库中所需的输出
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;
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。