我正在使用SQL Server 2008,甚至不知道从哪里开始计算。非常感谢您能提供的任何帮助。
我有两列,StartTime和EndTime。我有三个时间范围:上午12:00-上午7:59,白天8:00到3:59(或15:39)pm和晚上4:00 pm(或16:00)到11:59 (或23:59)下午。
我想计算每个范围内的StartTime和EndTime之间的小时数。例如,对于下面的第一行,从6:00到17:00之间有11个小时,早上有2个小时,白天有8个小时,晚上有1个小时。因此,我需要四列:一列用于11个小时,一列用于早晨,白天和傍晚。
StartTime EndTime
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
所需结果,使用第一个结果
NbrHours = 11
MorningHrs = 2
DayHrs = 8
EveningHrs = 1
答案 0 :(得分:1)
与此类似的事情应该可以帮到您...
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
;