Oracle SQL-从带有日期的表开始/结束日期
我有一个问题,我不知道如何解决它: 我有以下资料: 产品 你买什么 日期 A. 1. 01/01/2021 A. 1. 02/01/2021 A. 1. 03/01/2021 A. 0 04/01/2021 A. 1. 05/01/2021 A. 1. 06/01/2021 B 1. 01/01/2021 C 1. 01/01/2021 C 0 02/01/2021 C 0 03/01/2021 C 1. 04/01/2021Oracle SQL-从带有日期的表开始/结束日期,oracle,pattern-matching,gaps-and-islands,Oracle,Pattern Matching,Gaps And Islands,我有一个问题,我不知道如何解决它: 我有以下资料: 产品 你买什么 日期 A. 1. 01/01/2021 A. 1. 02/01/2021 A. 1. 03/01/2021 A. 0 04/01/2021 A. 1. 05/01/2021 A. 1. 06/01/2021 B 1. 01/01/2021 C 1. 01/01/2021 C 0 02/01/2021 C 0 03/01/2021 C 1. 04/01/2021 你没有告诉我们你的Oracle版本。下面我将展示两种解决方案:首先是
你没有告诉我们你的Oracle版本。下面我将展示两种解决方案:首先是更高级的解决方案,使用Oracle 12.1中添加的
match\u 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\u date
第一种解决方案,使用match\u 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方法):
试试这个
Select
Product,
Is_Buy,
(select min(x.DATE) from products x where x.product=a.product and x.is_buy=a.is_buy) from_date,
(select max(x.DATE) from products x where x.product=a.product and x.is_buy=a.is_buy) to_date,
from products a
group by a.Product, a.Is_Buy
请注意:Oracle SQL不称为“PL/SQL”。PL/SQL是完全不同的。我不会告诉你它是什么-我相信你可以使用谷歌搜索找到。我相应地更改了您的标签(以及问题的标题)。
Select
Product,
Is_Buy,
(select min(x.DATE) from products x where x.product=a.product and x.is_buy=a.is_buy) from_date,
(select max(x.DATE) from products x where x.product=a.product and x.is_buy=a.is_buy) to_date,
from products a
group by a.Product, a.Is_Buy