|
数据给的不用心啊
4 D 2017/03/31 2017/04/31
5 E 2017/03/01 2017/04/31
这哪里有4月31号
跟着newkid学了一下
with tmp as
(select 1 line_num,
'A' item,
to_date('2017/03/01', 'yyyy/mm/dd') date_from,
to_date('2017/03/31', 'yyyy/mm/dd') date_to
from dual
union all
select 2,
'B',
to_date('2017/03/01', 'yyyy/mm/dd'),
to_date('2017/03/31', 'yyyy/mm/dd')
from dual
union all
select 3,
'C',
to_date('2017/03/01', 'yyyy/mm/dd'),
to_date('2017/03/31', 'yyyy/mm/dd')
from dual
union all
select 4,
'D',
to_date('2017/03/31', 'yyyy/mm/dd'),
to_date('2017/04/30', 'yyyy/mm/dd')
from dual
union all
select 5,
'E',
to_date('2017/03/01', 'yyyy/mm/dd'),
to_date('2017/04/30', 'yyyy/mm/dd')
from dual
union all
select 6,
'F',
to_date('2017/01/01', 'yyyy/mm/dd'),
to_date('2017/02/28', 'yyyy/mm/dd')
from dual
union all
select 7,
'G',
to_date('2017/05/01', 'yyyy/mm/dd'),
to_date('2017/05/31', 'yyyy/mm/dd')
from dual
union all
select 8,
'H',
to_date('2017/05/01', 'yyyy/mm/dd'),
to_date('2017/07/31', 'yyyy/mm/dd')
from dual),
tmp2 as
(select t.*,
(case
when date_from <= max(date_to)
over(order by date_from,
date_to rows between unbounded preceding and 1 preceding) then
0
else
1
end) broken
from tmp t),
tmp3 as
(select line_num,
item,
date_from,
date_to,
sum(broken) over(order by date_from, date_to) flag
from tmp2),
tmp4 as
(select min(date_from) start_date, max(date_to) end_Date
from tmp3
group by flag)
select count(1) cnt, start_Date, end_Date
from tmp t
left join tmp4
on date_from >= start_date
and date_to <= end_date
group by start_Date, end_Date
order by start_Date;
 |
|