我有一个表foo
,其中包含id
列(非唯一),start_date
和end_date
。对于具有特定id
的所有行,我希望没有[start_date
,end_date
)范围重叠。我想通过更改有问题的行的end_date
来做到这一点。
我有
update foo old
set end_date = new.start_date
from foo new
where old.start_date < new.start_date and old.end_date > new.start_date
and old.id = new.id and new.id = 8675309;
但是,如果old
与其他多条记录重叠,则无法正常工作。我最好的尝试是
update foo old
set end_date = (select coalesce(min(new.start_date), old.end_date)
from foo new
where old.start_date < new.start_date and old.end_date > new.start_date
and new.id = old.id)
where old.id = 8675309;
这样可行,但它会不必要地更新每一行,感觉就像一个黑客。最好的方法是什么?
答案 0 :(得分:0)
这假设start_date
在id
update foo
set end_date = s.lsd
from (
select
id, start_date,
lead (start_date, 1, end_date) over (
partition by id order by start_date
) as lsd
from foo
) s
where
foo.id = s.id and
foo.start_date = s.start_date and
foo.end_date > s.lsd