MERGE INTO table_name t
USING (
SELECT rowid AS rid,
rn,
MAX(enddate) OVER (PARTITION BY mn) AS enddate
FROM table_name
MATCH_RECOGNIZE (
PARTITION BY id, code
ORDER BY startdate, enddate
MEASURES
COUNT(*) AS rn,
MATCH_NUMBER() AS mn
ALL ROWS PER MATCH
PATTERN ( overlap* last_row )
DEFINE overlap AS NEXT(startdate) <= MAX(enddate) + 1
)
) m
ON (t.ROWID = m.rid)
WHEN MATCHED THEN
UPDATE
SET enddate = m.enddate
DELETE WHERE rn > 1
其中,对于样本数据:
CREATE TABLE table_name (id, code, startdate, enddate) AS
SELECT 1, 'X', DATE '2023-01-01', DATE '2023-01-30' FROM DUAL UNION ALL
SELECT 1, 'X', DATE '2023-02-01', DATE '2023-02-28' FROM DUAL UNION ALL
SELECT 1, 'X', DATE '2023-02-10', DATE '2023-02-28' FROM DUAL UNION ALL
SELECT 1, 'Y', DATE '2023-01-01', DATE '2023-01-31' FROM DUAL UNION ALL
SELECT 1, 'Y', DATE '2023-02-01', DATE '2023-02-28' FROM DUAL UNION ALL
SELECT 1, 'Y', DATE '2023-03-01', DATE '2023-03-31' FROM DUAL;
1条答案
按热度按时间8tntrjer1#
您可以使用
MERGE
语句和MATCH_RECOGNIZE
来查找重叠:其中,对于样本数据:
在
MERGE
之后,该表包含:| ID|代码|开始日期|结束|
| --------------|--------------|--------------|--------------|
| 1| X| 2019 -01- 21 00:00:00| 2023-03-31 00:00:00|
| 1| X| 2019 -02- 21 00:00:00| 2019 -02-28 00:00:00|
| 1| Y轴|2019 -01- 21 00:00:00| 2023-03-31 00:00:00|
fiddle