问题
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