您没有告诉我们您的 Oracle 版本。下面我将展示两个解决方案:第一个是更高级的,使用 Oracle 12.1 中添加的 match_recognize 子句,然后是旧的方法,使用 Tabibitosan 方法解决间隙和岛屿问题(您的问题所属的类到)。
数据设置:
create table my_data (product, is_buy, eff_date) as
select 'A', 1, to_date('01/01/2021', 'mm/dd/yyyy') from dual union all
select 'A', 1, to_date('02/01/2021', 'mm/dd/yyyy') from dual union all
select 'A', 1, to_date('03/01/2021', 'mm/dd/yyyy') from dual union all
select 'A', 0, to_date('04/01/2021', 'mm/dd/yyyy') from dual union all
select 'A', 1, to_date('05/01/2021', 'mm/dd/yyyy') from dual union all
select 'A', 1, to_date('06/01/2021', 'mm/dd/yyyy') from dual union all
select 'B', 1, to_date('01/01/2021', 'mm/dd/yyyy') from dual union all
select 'C', 1, to_date('01/01/2021', 'mm/dd/yyyy') from dual union all
select 'C', 0, to_date('02/01/2021', 'mm/dd/yyyy') from dual union all
select 'C', 0, to_date('03/01/2021', 'mm/dd/yyyy') from dual union all
select 'C', 1, to_date('04/01/2021', 'mm/dd/yyyy') from dual
;
(顺便说一下,这是在您的帖子中包含示例数据的首选方式!)
注意date是保留关键字;我将列名更改为eff_date。
第一个解决方案,使用match_recognize匹配数据中的模式:
select product, is_buy, eff_date, end_date
from my_data
match_recognize(
partition by product
order by eff_date
measures a.is_buy as is_buy,
a.eff_date as eff_date,
next(eff_date) as end_date
pattern ( a b* )
define b as is_buy = a.is_buy
);
PRODUCT IS_BUY EFF_DATE END_DATE
------- ------ ---------- ----------
A 1 01/01/2021 04/01/2021
A 0 04/01/2021 05/01/2021
A 1 05/01/2021
B 1 01/01/2021
C 1 01/01/2021 02/01/2021
C 0 02/01/2021 04/01/2021
C 1 04/01/2021
第二种解决方案,仅使用解析函数和聚合(Tabibitosan 方法):
with prep as (
select product, is_buy, eff_date,
lead(eff_date) over (partition by product
order by eff_date) as next_date,
row_number() over (partition by product order by eff_date) -
row_number() over (partition by product, is_buy order by eff_date)
as grp
from my_data
)
select product, is_buy, min(eff_date) as eff_date,
max(next_date) keep (dense_rank last order by eff_date) as end_date
from prep
group by product, is_buy, grp
order by product, eff_date
;