每天以设定的时间间隔

时间:2016-02-10 22:46:44

标签: sql sql-server tsql

我正在尝试执行查询,该查询在30天内返回以下结果。有人可以告诉我如何在一个月内执行以下查询吗?

所以我想要的结果是日期时间字段的每日范围,时间是第二天早上7点到早上7点。我在下面的查询仅提供特定日期的数据。如果可能的话,我希望在@start和@end之间的固定时间段内完成。

标记名|日期|结果

Declare @start date, @end date;
set @start = '20160101';
set @end = '20160201';

select tagname, max(value) - min(value) as myRange
from runtime.dbo.AnalogHistory
where tagname = 'SALV_CV005_WX1_TOTAL.PVAI' and datetime between dateadd(hh,7,convert(datetime,@start)) and dateadd(hh,31,convert(datetime,@start))
group by TagName

我想要的结果应该在

之下
date    | tagname | (daily range) 
1/1/16  | XXXX    | 12354
2/1/16  | XXXX    | 2354
3/1/16  | XXXX    | etc

2 个答案:

答案 0 :(得分:1)

如果我理解正确,你想要在上午7点开始一天。如果是这样,那么计算从日期/时间减去7小时后的日期。如果您不关心索引:

Declare @start datetime, @end datetime;
set @start = '20160101';
set @end = '20160201';

select cast(dateadd(hour, -7, datetime) as date) as thedate,
       ah.tagname, max(ah.value) - min(ah.value) as myRange
from runtime.dbo.AnalogHistory ah
where ah.tagname = 'SALV_CV005_WX1_TOTAL.PVAI' and
      cast(dateadd(hour, -7, datetime) as date) between @start and dateadd(day, 1, @end)
group by cast(dateadd(hour, -7, datetime) as date), TagName
order by thedate, tagname;

答案 1 :(得分:0)

尝试:

Declare @start date, @end date;
set @start = '20160101';
set @end = '20163001';

select dateadd(DAY,0, datediff(day,0, datetime))
, tagname
, max(value) - min(value) as myRange
from runtime.dbo.AnalogHistory
where tagname = 'SALV_CV005_WX1_TOTAL.PVAI' 
    and datetime between @start and @end
group by TagName, dateadd(DAY,0, datediff(day,0, datetime))

使用@start和@end的日期范围。 dateadd(DAY,0,datediff(day,0,datetime))将返回日期时间的日期,您可以将其分组。