我有一张表,每分钟都会记录一次数据。它看起来像:
time_stamp wh
2013-02-01 08:00:00 1700
2013-02-01 08:01:00 1600
2013-02-01 08:02:00 1800
2013-02-01 08:03:00 1700
2013-02-01 08:04:00 1900
2013-02-01 08:05:00 1400
2013-02-01 08:06:00 1500
2013-02-01 08:07:00 1700
2013-02-01 08:08:00 1700
2013-02-01 08:09:00 1800
2013-02-01 08:10:00 1800
2013-02-01 08:11:00 1400
...等
我想每3分钟总结一次数据,每3分钟找一次平均值。 输出结果如下:
time_stamp SUM(wh) AVG(wh)
2013-02-01 08:00:00 5100 1700
2013-02-01 08:03:00 5500 1833.3333
2013-02-01 08:06:00 4900 1633.3333
2013-02-01 08:09:00 5000 1666.6667
这似乎很容易,但我无法得到我想要的结果。这是我试过的SQL查询:
SELECT from_unixtime(ROUND(unix_timestamp(time_stamp) /
(60*3)) * 60 * 3) AS rounded_time,
SUM(wh),
AVG(wh)
FROM electrex_0
WHERE time_stamp BETWEEN '2013-02-01 08:00' AND '2013-02-01 09:00'
GROUP BY rounded_time
通过使用此sql代码,我设法正确获取time_stamp,但不是SUM
和AVG
。我意识到它将以另一种方式总结。例如:2013-02-01 08:03:00的Sum(wh)
是5100,它将从08:02,08:03,08:04获取数据并总结一下。
答案 0 :(得分:1)
你想如何从5500获得:
2013-02-01 08:03:00 1700
2013-02-01 08:04:00 1900
2013-02-01 08:05:00 1400
总计达5000,不是吗?
以下是您的查询已修复以返回正确的数据:
SELECT
from_unixtime(ROUND((unix_timestamp(time_stamp) - 60) / (60*3)) * 60 * 3) AS rounded_time,
SUM(wh),
AVG(wh)
FROM electrex_0
WHERE time_stamp BETWEEN '2013-02-01 08:00'
AND '2013-02-01 09:00'
GROUP BY rounded_time
返回:
ROUNDED_TIME SUM(WH) AVG(WH)
February, 01 2013 08:00:00+0000 5100 1700
February, 01 2013 08:03:00+0000 5000 1666.6667
February, 01 2013 08:06:00+0000 4900 1633.3333
February, 01 2013 08:09:00+0000 5000 1666.6667
答案 1 :(得分:1)
以下是使用变量
的方法SET @VAR:=1;
SET @group=0;
SELECT
time_stamp,
SUM(wh) AS `TotalSum`,
AVG(wh) AS `TotalAvg`
FROM
(
SELECT
time_stamp,
wh,
@VAR AS Level,
@group AS `TGroup`,
@group := IF(@VAR = 3,@group + 1 ,@group) ,
@VAR := IF(@VAR = 3,1,@VAR+1 )
FROM electrex_0
) AS l
GROUP BY TGroup
输出
| TIME_STAMP | TOTALSUM | TOTALAVG |
----------------------------------------------------------
| February, 01 2013 08:00:00+0000 | 5100 | 1700 |
| February, 01 2013 08:03:00+0000 | 5000 | 1666.6667 |
| February, 01 2013 08:06:00+0000 | 4900 | 1633.3333 |
| February, 01 2013 08:09:00+0000 | 5000 | 1666.6667 |