如何合并 SQL 中的记录开始日期和结束日期
How to combine records start date and end date in SQL
我有一组数据示例如下:
ID
Role
START_DATE
END_DATE
1
A
2022-02-01
2022-02-03
1
A
2022-02-03
2022-02-10
1
A
2022-02-10
9000-12-31
2
B
2022-02-01
2022-02-03
2
A
2022-02-03
2022-02-04
2
B
2022-02-04
2022-02-11
我想根据 ID、ROLE、START_DATE 和 END_DATE 对它们进行分组。所以它看起来像下面这样:
x
ID
Role
START_DATE
END_DATE
1
A
2022-02-01
9000-12-31
2
B
2022-02-01
2022-02-03
2
A
2022-02-03
2022-02-04
2
B
2022-02-04
2022-02-11
我怎样才能做到这一点?
谢谢
Teradata 的 NORMALIZE 的简单任务:
with cte as
( -- works on PERIODs only
select NORMALIZE -- combine overlapping periods
ID, Role, period(START_DATE, END_DATE) as pd
from mytable
)
-- split period back into start/end
select ID, Role, begin(pd) as START_DATE, end(pd) as END_DATE
from cte
我有一组数据示例如下:
ID | Role | START_DATE | END_DATE |
---|---|---|---|
1 | A | 2022-02-01 | 2022-02-03 |
1 | A | 2022-02-03 | 2022-02-10 |
1 | A | 2022-02-10 | 9000-12-31 |
2 | B | 2022-02-01 | 2022-02-03 |
2 | A | 2022-02-03 | 2022-02-04 |
2 | B | 2022-02-04 | 2022-02-11 |
我想根据 ID、ROLE、START_DATE 和 END_DATE 对它们进行分组。所以它看起来像下面这样: x
ID | Role | START_DATE | END_DATE |
---|---|---|---|
1 | A | 2022-02-01 | 9000-12-31 |
2 | B | 2022-02-01 | 2022-02-03 |
2 | A | 2022-02-03 | 2022-02-04 |
2 | B | 2022-02-04 | 2022-02-11 |
我怎样才能做到这一点?
谢谢
Teradata 的 NORMALIZE 的简单任务:
with cte as
( -- works on PERIODs only
select NORMALIZE -- combine overlapping periods
ID, Role, period(START_DATE, END_DATE) as pd
from mytable
)
-- split period back into start/end
select ID, Role, begin(pd) as START_DATE, end(pd) as END_DATE
from cte