您可以使用该lead
函数查看下一行并获取其生效日期:
select person_id, effective_date,
lead(effective_date)
over (partition by person_id order by effective_date) as lead_date
from t42;
PERSON_ID EFFECTIVE_DATE LEAD_DATE
---------- -------------- ---------
6335 26-JUN-98 09-JUL-98
6335 09-JUL-98 24-FEB-99
6335 24-FEB-99
然后,您可以使用它来执行更新。该merge
命令使这很容易:
merge into t42
using (
select person_id, effective_date,
lead(effective_date)
over (partition by person_id order by effective_date) as lead_date
from t42
) t
on (t42.person_id = t.person_id and t42.effective_date = t.effective_date)
when matched then
update set t42.end_effective_date =
case
when t.lead_date is null then date '9999-12-31'
else t.lead_date - 1
end;
3 rows merged.
select * from t42;
PERSON_ID EFFECTIVE_DATE END_EFFECTIVE_DATE
---------- -------------- ------------------
6335 26-JUN-98 08-JUL-98
6335 09-JUL-98 23-FEB-99
6335 24-FEB-99 31-DEC-99
该using
子句具有上面的代码段,从前一行获取日期。该on
子句将此与您的原始表相匹配,并且对于匹配的行,将结束生效日期更新为潜在客户生效日期的前一天,或者如果没有潜在客户值(对于最近的“当前”行),则使用固定日期从 1999 年开始。
您的问题涉及更新,但如果您只想将结束日期作为结果集中的计算列,则要简单得多:
select person_id, effective_date,
case when lead_date is null then date '9999-12-31'
else lead_date - 1 end as end_effective_date
from (
select person_id, effective_date,
lead(effective_date)
over (partition by person_id order by effective_date) as lead_date
from t42
);
PERSON_ID EFFECTIVE_DATE END_EFFECTIVE_DATE
---------- -------------- ------------------
6335 26-JUN-98 08-JUL-98
6335 09-JUL-98 23-FEB-99
6335 24-FEB-99 31-DEC-99