2

我有一个表格,每分钟记录一次数据。看起来像:

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 

..ETC

我想每 3 分钟总结一次 wh 数据,每 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 但不是 forSUMAVG. 我意识到它会以另一种方式总结。例如:Sum(wh)2013-02-01 08:03:00 是 5100,它将从 08:02,08:03,08:04 获取数据并总结。

4

2 回答 2

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

SQL 小提琴演示

输出

|     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 |
于 2013-03-20T09:07:49.553 回答
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

演示

于 2013-03-20T08:41:53.817 回答