Select data between 2 dates and average hourly output

别说谁变了你拦得住时间么 提交于 2021-02-17 03:55:32

问题


I am have a series of temperature data which is gathered every minute and put into a MySQL database. I want to write a query to select all temperatures for the last 24 hours then group and average them into hours. Is this possible via a SQL command?

I think its a case of selecting all records between the two date/times, but thats the point I get stuck.

Data Example:

ID    Temp      Timestamp
3922  22        2015-11-17 14:12:23
3923  22        2015-11-17 14:13:23
3924  22.05     2015-11-17 14:14:23
3925  22.05     2015-11-17 14:15:23

Needed output / Result

Temp   Time
22     2015-11-17 14:00:00
23     2015-11-17 15:00:00
23     2015-11-17 16:00:00
22.05  2015-11-17 17:00:00

I hope you can help as I am totally lost with SQL commands.


回答1:


Try this query

SELECT
   AVG(Temp) AS Temp,
   DATE_FORMAT(Timestamp, '%Y-%m-%d %H:00:00') AS Time
FROM Table
WHERE DATE_FORMAT(Timestamp, '%Y-%m-%d %H:00:00') >= DATE_FORMAT(DATE_ADD(NOW(), INTERVAL -1 DAY), '%Y-%m-%d %H:00:00')
GROUP BY DATE_FORMAT(Timestamp, '%Y-%m-%d %H:00:00')



回答2:


Yes, this is quite feasible in SQL. It is easiest to get the hour out as:

select hour(timestamp), avg(temp)
from t
where timestamp >= date_sub(now(), interval 1 day)
group by hour(timestamp);

This isn't perfect, because the first and last hour boundary is from a different day. So, this is more like the output you want:

select date_add(date(timestamp), interval hour(timestamp) hour) as `time`,
       avg(temp)
from t
where timestamp >= date_sub(now(), interval 1 day)
group by date_add(date(timestamp), interval hour(timestamp) hour);


来源:https://stackoverflow.com/questions/33760390/select-data-between-2-dates-and-average-hourly-output

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!