我解决了1天的问题但是当我将这些日子分成1天时,我遇到了问题。
declare @Start datetime
declare @Finish datetime
declare @TimeRange int
set @Start = N'2012-10-16 00:00:00.000'
set @Finish = N'2012-10-19 00:00:00.000'
set @TimeRange = 1
declare @TimeRanges as TABLE (SessionStart datetime, SessionEnd datetime);
with TimeRanges as
( select @Start as StartTime, DATEADD(day, @TimeRange, @Start) as EndTime
union all
select DATEADD(day, @TimeRange, StartTime), DATEADD(day, @TimeRange, EndTime)
from TimeRanges
where EndTime < @Finish
)
timeRanges表将@Start和@Finish分成几天。
以下是问题的开始:
select StartTime, EndTime,TMP.NoOfCalls
from (SELECT TOP 1 DATEADD(SECOND, Number, c.SessionStartTime) CallTime, COUNT(C.ScenarioID) NoOfCalls FROM test c
INNER JOIN Numbers N ON N.Number <= DATEDIFF(SECOND, C.SessionStartTime, C.SessionCloseTime)
where c.SessionStarttime >= @Start and c.SessionCloseTime <= @Finish
GROUP BY DATEADD(SECOND, Number, c.SessionStartTime)
ORDER BY NoOfCalls DESC
)as TMP left outer join TimeRanges as TR on @Start <= TR.StartTime and TR.EndTime <= @Finish
group by TR.StartTime, TR.EndTime,TMP.NoOfCalls
order by TR.StartTime
以下是我得到的结果:
实际上260是N'2012-10-17 00:00:00.000'和N'2012-10-18 00:00:00.000'之间的结果,但我想分开结果。
我的样本测试表:
SessionID SessionStartTime SessionCloseTime
24 2012-10-16 01:00:06.000 2012-10-16 01:01:22.000
24 2012-10-16 01:00:08.000 2012-10-16 01:01:10.000
24 2012-10-16 01:00:16.000 2012-10-16 01:01:12.000
24 2012-10-16 01:00:30.000 2012-10-16 01:01:48.000
24 2012-10-16 01:00:41.000 2012-10-16 01:02:08.000
24 2012-10-16 01:00:48.000 2012-10-16 01:01:34.000
24 2012-10-16 01:00:56.000 2012-10-16 01:03:09.000
24 2012-10-16 01:01:02.000 2012-10-16 01:02:13.000
24 2012-10-16 01:01:05.000 2012-10-16 01:03:16.000
24 2012-10-16 01:01:09.000 2012-10-16 01:02:42.000
24 2012-10-16 01:01:15.000 2012-10-16 01:02:48.000
24 2012-10-16 01:01:18.000 2012-10-16 01:02:14.000
24 2012-10-16 01:01:18.000 2012-10-16 01:02:06.000
24 2012-10-16 01:01:42.000 2012-10-16 01:03:16.000
24 2012-10-16 01:01:45.000 2012-10-16 01:03:04.000
答案 0 :(得分:0)
您的问题是左连接,但您的查询似乎过于复杂。
尝试
with TimeRanges as
( select @Start as StartTime, DATEADD(day, @TimeRange, @Start) as EndTime
union all
select DATEADD(day, @TimeRange, StartTime), DATEADD(day, @TimeRange, EndTime)
from TimeRanges
where EndTime < @Finish
)
select TimeRanges.StartTime, TimeRanges.EndTime, COUNT(*)
from TimeRanges
inner join YourTable Sess
on sess.sessionstarttime>TimeRanges.StartTime
and sess.sessionclosetime< TimeRanges.EndTime
group by TimeRanges.StartTime, TimeRanges.EndTime