時間範囲は次のように決定できます。
declare @StartTime as DateTime = '10-02-2012 10:00'
declare @EndTime as DateTime ='10-02-2012 11:00'
declare @TimeRange as Time = '00:05:00.000'
; with TimeRanges as (
select @StartTime as StartTime, @StartTime + @TimeRange as EndTime
union all
select StartTime + @TimeRange, EndTime + @TimeRange
from TimeRanges
where EndTime < @EndTime ) -- Corrected.
select StartTime, EndTime
from TimeRanges
範囲をサンプル データと結合して、概要を取得します。
declare @StartTime as DateTime = '10-02-2012 10:00'
declare @EndTime as DateTime ='10-02-2012 11:00'
declare @TimeRange as Time = '00:05:00.000'
declare @Samples as Table ( SampleId Int Identity, SampleTime DateTime )
insert into @Samples ( SampleTime ) values
( '10-02-2012 9:00' ), ( '10-02-2012 10:00' ), ( '10-02-2012 10:02' ), ( '10-02-2012 10:02' ),
( '10-02-2012 10:05' ), ( '10-02-2012 10:20' ), ( '10-02-2012 10:34' ), ( '10-02-2012 11:30' )
; with TimeRanges as (
select @StartTime as StartTime, @StartTime + @TimeRange as EndTime
union all
select StartTime + @TimeRange, EndTime + @TimeRange
from TimeRanges
where EndTime < @EndTime ) -- Corrected.
select StartTime, EndTime, Count( S.SampleId ) as Samples
from TimeRanges as TR left outer join
@Samples as S on TR.StartTime <= S.SampleTime and S.SampleTime < TR.EndTime
group by TR.StartTime, TR.EndTime