Что-то похожее на это должно помочь вам ...
drop table if exists #times;
go
create table #times(
StartTime datetime ,
EndTime datetime
);
insert #times values
('2017-10-25 06:00:00.000', '2017-10-25 17:00:00.000'),
('2017-10-26 05:30:00.000', '2017-10-26 18:00:00.000'),
('2017-10-30 07:00:00.000', '2017-10-30 17:30:00.000'),
('2017-11-01 06:00:00.000', '2017-11-01 17:30:00.000'),
('2017-10-06 04:00:00.000', '2017-10-06 05:00:00.000'),
('2016-04-28 04:00:00.000', '2016-04-28 10:00:00.000'),
('2017-06-30 04:00:00.000', '2017-07-01 00:00:00.000'),
('2016-01-26 06:30:00.000', '2016-01-26 19:00:00.000'),
('2017-08-15 07:00:00.000', '2017-08-15 19:30:00.000'),
('2016-01-28 07:00:00.000', '2016-01-28 19:30:00.000')
;
with
a as (
select StartTime ,
EndTime ,
datepart(hour, StartTime) as StartHour ,
datepart(hour, StartTime) + datediff(hour, StartTime, EndTime) as EndHour
from #times
)
select a.StartTime,
a.EndTime ,
StartHour ,
EndHour ,
EndHour - StartHour as Total ,
case when EndHour > 8 then 8 else EndHour end - case when StartHour < 0 then 0 else StartHour end as Morning ,
case when EndHour > 16 then 16 else EndHour end - case when StartHour < 8 then 8 else StartHour end as Afternoon ,
case when EndHour > 24 then 24 else EndHour end - case when StartHour < 16 then 16 else StartHour end as Evening
from a
;