重叠日期
Overlaping dates
*编辑 - 无更新权。
我有下表:一个 ID 应该只关联到一个区域。 TableB 上有重叠。因此,John 在 1/9/19 与 East 和 MidEast 地区相关联。
我可以操纵 TableB 来修复重叠吗?
所以,最旧的行 enddate (1/9/19) would change to 1/7/19.
重叠时间可以超过一天。
Lead
和/或Lag
在这里可以用吗?不知道从哪里开始。
表A
CustDate id Name
1/9/19 1 John
表B
StartDate EndDate AREA
1/1/2019 1/9/19 East
1/8/2019 12/31/4000 Mideast
示例SQL
,CASE WHEN ENDDATE >
LEAD(STARTDATE) OVER (PARTITION BY ID ORDER BY STARTDATE)
THEN MIN(ENDDATE) OVER (PARTITION BY ID) - interval '1' day
ELSE ENDATE
END END_DT2
您可以通过更新 enddate
:
来修复 TableB
update tableb b
set enddate = (select min(startdate) - interval '1' day
from tableb b2
where b2.startdate > b.startdate
);
或者,将其表示为 select
:
select b.startdate,
lead(b.startdate, 1, date '4000-12-31') over (order by b.startdate) - interval '1' day as enddate,
b.area
from tableb b;
也许 Lead
和 Lag
如下所示:
,CASE
WHEN ENDDATE > LEAD(STARTDATE) OVER (PARTITION BY ID ORDER BY STARTDATE)
THEN LEAD (STARTDATE) OVER (PARTITION BY ID ORDER BY STARTDATE) -1
ELSE ENDDATE
END END_DT
*编辑 - 无更新权。
我有下表:一个 ID 应该只关联到一个区域。 TableB 上有重叠。因此,John 在 1/9/19 与 East 和 MidEast 地区相关联。
我可以操纵 TableB 来修复重叠吗?
所以,最旧的行 enddate (1/9/19) would change to 1/7/19.
重叠时间可以超过一天。
Lead
和/或Lag
在这里可以用吗?不知道从哪里开始。
表A
CustDate id Name
1/9/19 1 John
表B
StartDate EndDate AREA
1/1/2019 1/9/19 East
1/8/2019 12/31/4000 Mideast
示例SQL
,CASE WHEN ENDDATE >
LEAD(STARTDATE) OVER (PARTITION BY ID ORDER BY STARTDATE)
THEN MIN(ENDDATE) OVER (PARTITION BY ID) - interval '1' day
ELSE ENDATE
END END_DT2
您可以通过更新 enddate
:
TableB
update tableb b
set enddate = (select min(startdate) - interval '1' day
from tableb b2
where b2.startdate > b.startdate
);
或者,将其表示为 select
:
select b.startdate,
lead(b.startdate, 1, date '4000-12-31') over (order by b.startdate) - interval '1' day as enddate,
b.area
from tableb b;
也许 Lead
和 Lag
如下所示:
,CASE
WHEN ENDDATE > LEAD(STARTDATE) OVER (PARTITION BY ID ORDER BY STARTDATE)
THEN LEAD (STARTDATE) OVER (PARTITION BY ID ORDER BY STARTDATE) -1
ELSE ENDDATE
END END_DT