
challenge..very tricky sql statement..please help
Terry,
Interesting problem. Here is a take on solving it. Fails if the modem is
in continuous use for more than 24 hours. Seems to work otherwise.
Russell Fields, MVP
drop table rlfRAS
go
/* Yes, use date time. Saves a lot of converting of character strings. */
create table rlfRAS (ComPort char(5), BeginTime datetime, EndTime datetime)
go
/* Test data points */
insert into rlfRAS values('COM28','02/04/98 09:35:39','02/04/98 09:36:31')
insert into rlfRAS values('COM28','02/04/98 09:38:39','02/04/98 09:45:31')
insert into rlfRAS values('COM30','02/04/98 09:35:39','02/04/98 11:36:02')
insert into rlfRAS values('COM28','02/04/98 12:00:00','02/04/98 13:00:01')
insert into rlfRAS values('COM30','02/04/98 21:35:39','02/05/98 01:36:02')
go
/* Create twenty-four hours */
drop table #HoursTable
go
create table #HoursTable (TheHour int)
go
begin
end
go
drop table #PortSeconds
go
create table #PortSeconds (ComPort char(5), TheHour int, SecondsUsed int)
go
Insert into #PortSeconds
select ComPort, TheHour, sum(
case
/* Within the Hour */
when (datepart(hour,BeginTime) = datepart(hour,EndTime)) then
datediff(second,BeginTime,EndTime)
else
case
/* Started in this hour, continues longer */
when (datepart(hour,BeginTime) = TheHour) then
datediff(second,BeginTime,
dateadd(hour, TheHour + 1,convert(datetime,
convert(char(10),BeginTime,6))))
/* Ended in this hour, started earlier. */
when (datepart(hour,EndTime) = TheHour) then
datediff (second,
dateadd(hour, TheHour,convert(datetime,
convert(char(10),EndTime,6))), EndTime)
/* The whole hour */
else
3600
end
end
)
SecondsUsed
from rlfRAS, rlfHoursTable
where
/* The OR is needed to handle periods that span midnight */
dateadd(hour, TheHour,dateadd(hour, datepart(hour,BeginTime) * -1,
BeginTime))
between BeginTime and EndTime
or
dateadd(hour, TheHour,dateadd(hour, datepart(hour,EndTime) * -1, EndTime))
between BeginTime and EndTime
/* Condense it to total time per ComPort per Hour */
group by ComPort, TheHour
/* Condense the intermediate results to a count of ComPorts used */
select count(ComPort) PortCount, TheHour, sum(SecondsUsed) SecondsUsed from
#PortSeconds
Where SecondsUsed > 1200 /* 20 minutes */
Group by TheHour