选择一个间隔的几个平均值

时间:2012-07-31 15:00:13

标签: mysql sql

所以我的同事正在研究一种可以描述为这样的模式:

+--------------------+-----------+
| DATETIME timestamp | INT value |
+--------------------+-----------+

每隔5分钟输入一行,其中包含该时刻的值。

这是它变得棘手的地方。他希望在7天的间隔内获得每8小时的平均值。

当然,我可以想到涉及一些客户端代码的解决方案,我们想知道是否有可能在SQL中做更多。

所以从本质上说,他想:

SELECT timestamp, value
  FROM table
 WHERE timestamp >= NOW() - INTERVAL 7 DAYS 
   AND timestamp <= NOW();

然后将其分解为8小时块,并平均每个块的内容。 (每个块应该有12行,每天应该有3个块)。

2 个答案:

答案 0 :(得分:1)

SELECT avg(`value`)
FROM `table`
WHERE timestamp >= NOW() - INTERVAL 7 DAY AND timestamp <= NOW()
group by concat(date(`timestamp`), case when hour(`timestamp`) between 0 and 7 then 1
                                        when hour(`timestamp`) between 8 and 15 then 2
                                        else 3 end)

答案 1 :(得分:0)

如果您不仅仅在请求中执行此操作,则可以在执行请求之前尝试以下方法拆分时间间隔:

boundary1 = NOW()
boundary2 = NOW()

FOR i = 0 to 21 //7 days, 3 intervals of 8 hours per days
    boundary1 = boundary2
    boundary2 = boundary1 - seconds(8 hours)
    req = "SELECT timestamp, value FROM table WHERE timestamp >= "+boundary2+" AND timestamp <= "+boundary1
ENDFOR