I have a table as you can see below :
create table z_test_duration
( Days date,
Status char(8)
);
Sample data is as below :
Days | Status |
---|---|
1/1/2022 | on |
1/2/2022 | on |
1/3/2022 | on |
1/4/2022 | off |
1/5/2022 | on |
1/6/2022 | off |
1/7/2022 | on |
1/8/2022 | on |
1/9/2022 | off |
The desired result is this
ON_DATE | OFF_DATE | COUNT_OF_ACTIVE_DAYS |
---|---|---|
1/1/2022 | 1/4/2022 | 3 |
1/5/2022 | 1/6/2022 | 1 |
1/7/2022 | 1/9/2022 | 2 |
My solution so far is this :
select min(days) on_date,
off_day off_date,
off_day - min(days) cnt
from (select t1.off_day,
t1.prev_offday,
t2.days
from (
select t.days off_day,
nvl(lag(t.days, 1) over(order by t.days),convert(datetime, '1/1/2022') - 100) prev_offday
from z_test_duration t
where t.status = 'off'
) t1
inner join z_test_duration t2
on t2.days > t1.prev_offday
and t2.days < t1.off_day)
group by off_day;
I'm thinking if there are better ways of solving this , It would be appreciated if you share your way of solving this .
Thanks in advance.