My try with hierarchical subquery generating days for each call and functions greatest
, least
:
SQLFiddle
with t as (
select id, sd, ed, trunc(sd)+level-1 dt
from calls
connect by trunc(sd)+level-1<=trunc(ed)
and prior dbms_random.value is not null and prior id = id)
select id, sum(sec) sec, sum(fri) fri, sum(mrn) mrn, sum(sec)-sum(mrn) rest
from (
select id, (least(ed, dt+1)-greatest(sd, dt))*24*60*60 sec,
case when trunc(dt) - trunc(dt, 'iw') = 4
then (least(dt+1, ed) - greatest(dt, sd)) * 24*60*60 end fri,
(least(dt+7.5/24, ed) - greatest(dt, sd)) * 24*60*60 mrn
from t )
group by id
Query version for "Fridays" - "non Fridays mornings" - "non Fridays rest of days" output (as precised in comments):
with cte as (
select id, sd, ed, trunc(sd)+level-1 dt from calls
connect by level <= trunc(ed)-trunc(sd) + 1
and prior dbms_random.value is not null and prior id = id )
select id, max(sd) start_time, max(ed) end_time,
sum(sec) all_seconds, sum(fri) fridays, sum(mrn) mornings,
sum(sec) - sum(fri) - sum(mrn) rest
from (
select id, sd, ed, dt, (least(ed, dt+1) - greatest(sd, dt))*24*60*60 sec,
case when dt - trunc(dt, 'iw') = 4
then (least(ed, dt+1) - greatest(sd, dt))*24*60*60 else 0 end fri,
case when dt - trunc(dt, 'iw') <> 4 and dt+7.5/24 > sd
then (least(dt+7.5/24, ed) - greatest(sd, dt))*24*60*60
else 0 end mrn
from cte )
group by id order by id
Sample data and output:
create table calls (id number(3), sd date, ed date);
insert into calls values (1, timestamp '2015-12-25 07:29:00', timestamp '2015-12-25 07:31:00');
insert into calls values (2, timestamp '2015-12-24 01:00:00', timestamp '2015-12-26 23:12:42');
insert into calls values (3, timestamp '2015-12-24 23:58:00', timestamp '2015-12-25 00:01:00');
insert into calls values (4, timestamp '2015-12-24 07:00:00', timestamp '2015-12-25 00:01:00');
ID START_TIME END_TIME ALL_SECONDS FRIDAYS MORNINGS REST
---- ------------------- ------------------- ----------- ---------- ---------- ----------
1 2015-12-25 07:29:00 2015-12-25 07:31:00 120 120 0 0
2 2015-12-24 01:00:00 2015-12-26 23:12:42 252762 86400 50400 115962
3 2015-12-24 23:58:00 2015-12-25 00:01:00 180 60 0 120
4 2015-12-24 07:00:00 2015-12-25 00:01:00 61260 60 1800 59400
Edit: