您可以这样确定时间范围:
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