1

我想在 TSQL 中编写一个程序,计算给定日期范围之间的峰值时间,这些日期范围分为给定时间。

Start time: 10-02-2012 10:00
End time  : 10-02 2012 11:00
time range: every 5 minutes

所以它将是:

10:00 range 1  -> 5 peak times
10:05 range 2  -> 11 peak times
.
.
.
11:00 range 11 -> 7 peak times

当给定时间范围 30 分钟时,代码将计算 2 个范围

我应该使用间隔吗?我怎么解决这个问题?有什么帮助吗?

4

2 回答 2

1

您可以这样确定时间范围:

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
于 2012-10-18T20:21:15.380 回答
0

使用带有 DATEADD 函数的循环。

http://msdn.microsoft.com/en-us/library/ms186819.aspx

继续添加您的“分钟”间隔,直到结果日期大于结束日期。

编辑

BEGIN
-- setup
DECLARE @start DATETIME
DECLARE @end DATETIME
DECLARE @interval INT
DECLARE @samples TABLE (
    [time] DATETIME
)
SET @start = CAST('10-02-2012 10:00' as DATETIME)
SET @end = CAST('10-02-2012 11:00' as DATETIME)
SET @interval = 5
INSERT INTO @samples 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' )
-- make the ranges
DECLARE @ranges TABLE (
    [start] datetime
    ,[end] datetime
)
DECLARE @tmp DATETIME
SET @tmp = DATEADD(minute, @interval, @start)
IF @tmp > @end BEGIN SET @tmp = @end END
WHILE @start < @end
    BEGIN
    INSERT INTO @ranges VALUES (@start, @tmp)
    SET @start = @tmp
    SET @tmp = DATEADD(minute, @interval, @start)
    IF @tmp > @end BEGIN SET @tmp = @end END
    END
-- execute the query
SELECT r.[start], r.[end], count(s.[time]) [count]
FROM @ranges r
    LEFT JOIN @samples s 
        ON r.[start] <= s.[time] AND r.[end] > s.[time]
GROUP BY r.[start], r.[end]
END

我建议使用一个简单的 while 循环来生成你想要的范围。对我来说,它比 CTE 递归查询解决方案更直接/易于理解,尽管公认的不那么优雅。

于 2012-10-18T20:01:09.287 回答