题35:
(1)首先通过子查询,将两个表拼接,过滤无用的数据;
select 'succeeded' as 'state',success_date as 'dt'
from Succeeded
where success_date between ' 2019-01-01' and '2019-12-31 '
union
select 'failed'as 'state',fail_date as 'dt'
from Failed
where fail_date between ' 2019-01-01' and '2019-12-31 '
(2)开窗作差,得到标记:subdate (date, INTERVAL expr unit),此函数有三个参数:
- 日期:第一个指定的日期;
- expr:要减去的时间日期间隔的值。
(3)根据标记分组,分别拿到这组的极值就是开始和结束日期。
select state as period_state,min(dt ) as start_date,max(dt) as end_date
from
(
select *,subdate(dt,rank()over(partition by state order by dt)) as dif
from
(
select 'succeeded' as 'state',success_date as 'dt'
from Succeeded
where success_date between ' 2019-01-01' and '2019-12-31 '
union
select 'failed'as 'state',fail_date as 'dt'
from Failed
where fail_date between ' 2019-01-01' and '2019-12-31 '
)t1
)t2
group by state,dif
order by dt;