计算时间间隔内的每小时平均值

时间:2014-12-10 21:41:47

标签: sql sql-server

我不是一个真正的sql家伙,所以也许我想要做的很简单,但我找不到一个简单的解决方案。

我有两个日期之间的一系列小时数据。像这样:

DATETIME            VALUE
-------------------------
2014-01-01 01:00    104
2014-01-01 02:00    56
...
2014-01-04 23:00    65
2014-01-05 00:00    145

我想要的是,每小时,获得该时刻每天的平均价值,所以我用这样的结果结束查询:

01:00    67.65
02:00    43.00
....
00:00    89.45

" 01:00"价值将是所有" 01:00"的平均值。每天的价值,等等。

算法很简单,但我的SQL技能很弱: - )

奖金

如果答案包含同一问题的变体,那将是非常棒的:按工作日和小时计算平均值,而不仅仅是按小时计算:

Monday  01:00    34.23
Monday  02:00    54.34
...
Monday  23:00    241.34
Tuesday 00:00    89.43
....
Sunday  23:00    49.33

2 个答案:

答案 0 :(得分:2)

您可以使用datenamedatepartgroup by

select datename(weekday, [datetime]) as [Day], 
       datepart(hour, [datetime]) as [Hour], 
       avg(value) as AvgValue,
       datepart(weekday, [datetime]) as [DayNo]
from table1
group by datename(weekday, [datetime]), datepart(weekday, [datetime]), 
         datepart(hour, [datetime])
order by datepart(weekday, [datetime]), datepart(hour, [datetime]) 

答案 1 :(得分:0)

以下是可用于按时间间隔分组的常规聚合查询的示例。

WITH intervals AS (
    SELECT DATEADD(hour, DATEDIFF(hour, '', DATETIME), '') AS TimeInterval
    ,VALUE
    FROM dbo.Foo
    )
SELECT
      TimeInterval
    , DATENAME(weekday, TimeInterval) AS Weekday
    , CAST(TimeInterval AS time)
    , AVG(VALUE) AS AvgValue
FROM intervals
GROUP BY TimeInterval
ORDER BY TimeInterval;