题目
数据
结果
解答
1.union 合并数据、筛选日期
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,a)-->date-a
3.最后,挑选出来,最小(start)、最大(end) 日期,然后按照状态分组、按照subdate函数的结果分组。
select state as period_state, min(dt ) as start_date, max(dt) as end_date
from
(
select *,rank()over(partition by state order by dt ) as rk ,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