用于从列和GROUP BY

时间:2017-02-08 22:37:16

标签: mysql sql database group-by average

我有一张这样的餐桌,包括几个气候措施(降雨率,温度等)。

mysql> select rain_rate, temperature, datetime from weather limit 10; 
+--------------+---------------+----------------------+
| rain_rate    | temperature   | datetime             |
+--------------+---------------+----------------------+
| 5.0000000000 | 24.4000000000 | 2017-02-08 16:00:56  |
| 1.0000000000 | 22.4000000000 | 2017-02-06 12:10:36  |
| 2.0000000000 | 28.7000000000 | 2017-02-02 13:57:15  |
| 5.0000000000 | 24.7000000000 | 2017-02-01 14:14:16  |
| 1.0000000000 | 16.1000000000 | 2017-01-08 06:01:26  |
| 2.0000000000 | 18.2000000000 | 2017-01-12 05:10:43  |
| 3.0000000000 | 11.9000000000 | 2017-01-10 06:20:54  |
| 4.0000000000 | 16.8000000000 | 2017-01-25 16:10:14  |
| 5.0000000000 | 24.4000000000 | 2016-12-18 23:10:56  |
| 4.0000000000 | 26.6000000000 | 2016-12-30 09:03:54  |
...

可以看出,时间戳(日期时间字段)不遵循任何模式。

我希望得到最后24个平均值的温度和rain_rate 按小时,以及一个具有相关小时数值的列,以24小时格式,按小时asc命令。

例如,如果我今天下午18:30执行查询,它应该返回这24行:

+-----------------+------------------+-------+
| avg(rain_rate)  | avg(temperature) | hour  |
+-----------------+------------------+-------+
| 3.5000000000    | 23.1000000000    | 19    |  |
| 1.0000000000    | 22.6000000000    | 20    |  |
| 3.5000000000    | 24.7000000000    | 21    |  |-> hours of "yesterday"
| 4.5000000000    | 23.8000000000    | 22    |  |
                    ...
| 2.0000000000    | 26.3000000000    | 13    |  |
| 1.5000000000    | 21.6000000000    | 14    |  |
| 7.0000000000    | 23.4000000000    | 15    |  |-> hours of "today"
| 2.5000000000    | 21.4000000000    | 16    |  | 
| 7.0000000000    | 21.2000000000    | 17    |  |
| 3.0000000000    | 25.3000000000    | 18    |  |

到目前为止我最好的尝试:

select avg(rain_rate), avg(temperature), hour(datetime) as hour
from weather
where (datetime >= now() - interval 24 hour)
group by hour(datetime) 
order by max(datetime) asc

看起来该查询返回字段的正确平均值,但 hour 字段似乎没有像我需要的那样排序,也不对应于平均值......

非常感谢任何帮助。 提前谢谢。

2 个答案:

答案 0 :(得分:3)

您想要在过去24小时内按小时计算平均值。

确定。这是一种方式:

select date(datetime), hour(datetime),
       avg(rain_rate), avg(temperature)
from weather 
where (datetime >= now() - interval 24 hour)
group by date(datetime), hour(datetime) 
order by min(datetime);

注意:距离当前时间24小时可能有点奇怪。你可以得到25行记录(有两个部分小时)。您可能需要此where

where datetime < curdate() + interval hour(now()) hour and
      datetime >= curdate() + interval hour(now()) - 24 hour 

答案 1 :(得分:0)

我想你必须尝试order by datetime

查询必须如下:

select avg(rain_rate), avg(temperature), hour(datetime) as hour
from weather
where (datetime >= now() - interval 24 hour)
group by hour(datetime) 
order by datetime asc;

我希望我能得到帮助。