每隔5分钟选择一次数据

时间:2016-04-06 09:25:17

标签: sql-server sql-server-2008

我有以下查询给我24小时间隔数据,我想每隔5分钟获取一次数据

IF OBJECT_ID('tempdb..#mytemptable') IS NOT NULL DROP TABLE #mytemptable; 
SELECT  AVG( CAST ([PT_100SCALED_VAL0] AS bigint)  ) AS PT_100SCALED_VAL0_AVERAGE 
INTO #MYTEMPTABLE  FROM ( SELECT t1.[timestamp], t1.[PT_100SCALED_VAL0] FROM 
[REPORT] t1 WHERE t1.[timestamp] >= '2016-01-06 00:00:00' and  t1.[timestamp] <='2016-01-06 23:59:59'   ) 
TEMPTABLE 
SELECT t1.[timestamp], t1.[PT_100SCALED_VAL0]  , RM_temp.* FROM [REPORT]
t1 , #MYTEMPTABLE RM_temp  WHERE  t1.[timestamp] >= '2016-01-06 00:00:00' and  t1.[timestamp] <='2016-01-06 23:59:59' -- This select will give the final result.

上述查询的结果是

timestamp   PT_100SCALED_VAL0   PT_100SCALED_VAL0_AVERAGE
2016-01-06 13:31:27.807 1   5
2016-01-06 13:32:27.810 2   5
2016-01-06 13:33:27.817 3   5
2016-01-06 13:34:27.827 4   5
2016-01-06 13:35:27.827 5   5
2016-01-06 13:36:27.837 6   5
2016-01-06 13:37:27.840 7   5
2016-01-06 13:38:27.847 8   5
2016-01-06 13:39:27.850 9   5

我的预期结果是

timestamp                 PT_100SCALED_VAL0 PT_100SCALED_VAL0_AVERAGE
2016-01-06 13:35:27.827   5                 5    
2016-01-06 13:39:27.850   9                 5

我尝试过使用with和partion by但是如果

,我会收到错误的语法错误

1 个答案:

答案 0 :(得分:0)

Declare @start datetime, @end datetime
Select @start=CAST(CAST(getdate() as date) as datetime), @end=CAST((DATEADD(DAY,1,@start)) as datetime)
;With DateTimeSequence( Dt ) as
(
    Select @start as Stime
        union all
    Select DATEADD(MINUTE,5,Dt)
        from DateTimeSequence
        where Dt < DATEADD(MINUTE,-5,@end) 
)select Dt as StartTime,DATEADD(MINUTE,5,Dt)  as EndTime from DateTimeSequence
Option (MaxRecursion 1000) 

将上述CTE与您的查询一起使用,并加入您的查询并根据需要使用。