在SQL中采用每小时平均值

时间:2012-03-16 20:33:14

标签: tsql ssms average

我有一个包含2个字段的SQL表:TimeStamp和Value。以下是一些数据的摘录。

2005-02-17 13:31:00     2
2005-02-17 13:46:00     3
2005-02-17 14:01:00     1.7
2005-02-17 14:16:00     2.3
2005-02-17 14:31:00     2
2005-02-17 14:46:00     2.5
2005-02-17 15:01:00     2.2
2005-02-17 15:16:00     2.4
2005-02-17 15:31:00     2.6
2005-02-17 15:46:00     2.6
2005-02-17 16:01:00     2.7

我正在尝试按时间平均值列值,但我似乎无法正常工作。最终输出将显示TimeStamp的起始小时,以及Value列的平均值。

对于最终输出,我希望得到一个完整的时间戳,而不仅仅是小时。所以从2005-02-17的14:00到14:59,结果输出将是:

2005-02-17 14:00:00    2.125

5 个答案:

答案 0 :(得分:4)

select Time_Stamp_Hour=dateadd(hh,datepart(hh,Time_Stamp), cast(CAST(Time_Stamp as date) as datetime))
, AvgValue=AVG(Value)
from ValueLog
group by dateadd(hh,datepart(hh,Time_Stamp), cast(CAST(Time_Stamp as date) as datetime))

结果:

Time_Stamp_Hour         AvgValue
----------------------- ----------------------
2005-02-17 13:00:00.000 2.5
2005-02-17 14:00:00.000 2.125
2005-02-17 15:00:00.000 2.45
2005-02-17 16:00:00.000 2.7

兼容性:Sql Server 2008 +

答案 1 :(得分:4)

我会这样做:

SELECT      CAST(FLOOR(CAST(timestamp AS float)) AS datetime) AS day --strip time
            , DATEPART(hh, timestamp) AS hour
            , AVG(value) AS average
FROM        times
GROUP BY    CAST(FLOOR(CAST(timestamp AS float)) AS datetime)
            , DATEPART(hh, timestamp)

示例fiddle

答案 2 :(得分:3)

SELECT DATEPART(hour,Col1) as hourcol,AVG(Col2)
FROM Yourtable
GROUP BY hourcol;

OR

SELECT SUBSTRING(Col1,1,14)+'00' AS hourcol,AVG(Col2)
FROM Yourtable
GROUP BY hourcol;

在此查询中,DATEPART函数计算DATETIME列中所有值的小时值,并根据每小时计算第二列的平均值,以小时为单位。

答案 3 :(得分:0)

我想你也希望它按日期分组,而不仅仅是按小时,对吗?

select
  convert(VARCHAR(10), date, 111) as aDate,
  datepart(HH, date) anHour,
  avg(value) anAverage
from t
group by convert(VARCHAR(10), date, 111), datepart(HH, date)

或者这个:

; with aTable as (
select
  convert(VARCHAR(10), date, 111) as aDate,
  datepart(HH, date) anHour,
  value
from t)
select aDate, anHour, avg(value) from aTable
group by aDate, anHour

答案 4 :(得分:0)

SELECT
    AVG(myvalue) [Average],
    DATEADD(HOUR, DATEPART(HOUR, mydate), CAST(CAST(mydate as Date) as datetime)) [Hour]
FROM
    myTable
GROUP BY
    DATEADD(HOUR, DATEPART(HOUR, mydate), CAST(CAST(mydate as Date) as datetime))
ORDER BY
    DATEADD(HOUR, DATEPART(HOUR, mydate), CAST(CAST(mydate as Date) as datetime))