我有下表:
oDateTime Value
----------------------------------------------
2017-01-01 00:00:00 10
2017-01-01 00:00:01 20
2017-01-01 00:00:02 10
2017-01-01 00:00:03 10
ff.
每行日期的行数据为每秒。我希望得到以下结果:
oDateTime Value
----------------------------------------------
2017-01-01 01:00:00 10
所以它是每个日期的小时平均值 知道怎么做吗?
谢谢。
答案 0 :(得分:1)
DATEADD(HOUR, DATEDIFF(HOUR, 0, oDateTime), 0)
会将任何DATETIME值舍入到小时。这使您可以将DateHour值保持为单个列。
SELECT
DATEADD(HOUR, DATEDIFF(HOUR, 0, oDateTime), 0),
SUM(value) / 60.0,
AVG(value)
FROM
yourTable
GROUP BY
DATEADD(HOUR, DATEDIFF(HOUR, 0, oDateTime), 0)
编辑 :减少重复次数,但稍长一点......
SELECT
rounded.DateHour,
SUM(value) / 60.0,
AVG(value)
FROM
yourTable
CROSS APPLY
(VALUES(DATEADD(HOUR, DATEDIFF(HOUR, 0, oDateTime), 0))) AS rounded(dateHour)
GROUP BY
rounded.DateHour
答案 1 :(得分:0)
尝试按日期和小时进行汇总:
SELECT
CONVERT(varchar, oDateTime, 112) AS date,
DATEPART(hour, oDateTime) AS hour,
AVG(Value) AS Value
FROM yourTable
GROUP BY
CONVERT(varchar, oDateTime, 112),
DATEPART(hour, oDateTime);