2016-04-27 170 views
1

我正在编写一个查询,该查询应该采用属于特定日期范围内的值并吐出其平均值。但是,我遇到了一些麻烦。平均值在特定日期范围内?

基本上,我有一个大型数据集,它有30天以上的多个不同的数据子集。我需要弄清楚如何从9点到早上9点的两天内取平均值。

我的数据集的一个例子:

Device1  Values  TimeFrame 
---------------------------------------------------------   
Device1  Value1  2016-03-27 00:03:11.000 0.0019 
Device1  Value2  2016-03-27 00:03:11.000 18.7041 
Device1  Value3  2016-03-27 00:03:11.000 49.5902 
Device1  Value1  2016-03-27 00:08:06.000 0.0019 
Device1  Value2  2016-03-27 00:08:06.000 18.7041 
Device1  Value3  2016-03-27 00:08:06.000 49.5902 
Device1  Value1  2016-03-27 00:13:09.000 0.0019 
Device1  Value2  2016-03-27 00:13:09.000 18.7041 
Device1  Value3  2016-03-27 00:13:09.000 49.5902 
Device1  Value1  2016-03-28 00:03:11.000 0.0019 
Device1  Value2  2016-03-28 00:03:11.000 18.7041 
Device1  Value3  2016-03-28 00:03:11.000 49.5902 
Device1  Value1  2016-03-28 00:08:06.000 0.0019 
Device1  Value2  2016-03-28 00:08:06.000 18.7041 
Device1  Value3  2016-03-28 00:08:06.000 49.5902 
Device1  Value1  2016-03-28 00:13:09.000 0.0019 
Device1  Value2  2016-03-28 00:13:09.000 18.7041 
Device1  Value3  2016-03-28 00:13:09.000 49.5902 

我需要计算的平均值为每一天的每个值,但假定这一天开始于上午9时至次日上午9点结束。这有点过分。我不太确定从哪里开始。

回答

4

您可以通过减去9小时使用group by做到这一点:

select cast(dateadd(hour, -9, timeframe) as date) as thedate, 
     count(*) as num, avg(value) as avg_value 
from dataset t 
group by cast(dateadd(hour, -9, timeframe) as date) 
order by thedate;