您可以使用该lag
函数来引用前一行的值(定义“上一个”的含义作为查询的一部分;我假设您的“行号”是一个伪列,而不是您可以订购的实际列,并且您希望它们按开始日期顺序排列):
select start_date, end_date,
case
when lag_end_date is null then start_date
when lag_end_date = start_date then start_date
else lag_end_date
end as adj_start_date
from (
select start_date, end_date,
lag(end_date) over (order by start_date, end_date) as lag_end_date
from <your_table>
)
(SQL 小提琴)。
的第一个when
子句case
处理“第一”行,最早的开始日期;因为没有前一行,lag
所以将是null
。
start_date
然后,您可以过滤结果以获取那些adj_start_date
不匹配的结果。(另一个 SQL 小提琴)。
您可以在 a 中使用相同类型的构造merge
来进行更新:
merge into <your table>
using (
select r_id, start_date, end_date,
case when lag_end_date is null then null
when lag_end_date = start_date then null
else lag_end_date
end as adj_start_date
from (
select rowid as r_id, start_date, end_date,
lag(end_date) over (order by start_date, end_date) as lag_end_date
from t42
)
) t
on (your_table>.rowid = t.r_id and t.adj_start_date is not null)
when matched then
update set <your table>.start_date = t.adj_start_date;
(SQL 小提琴)。