Tony
Tony

Reputation: 825

Select data between 2 dates and average hourly output

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.

Upvotes: 1

Views: 948

Answers (2)

Mattia Caputo
Mattia Caputo

Reputation: 969

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')

Upvotes: 2

Gordon Linoff
Gordon Linoff

Reputation: 1271003

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);

Upvotes: 0

Related Questions