I have a table in MySQL with some data of a temperature sensor. I have 1 row per minute. I would like to perform a query to know whether there was any span of 1 hour where the average temperature was greater than 4 degrees. I know how to perform a query where a single row was above 4:
SELECT * FROM sensor WHERE t>4
But in my case, I want to know whether there was a 1 hour period where the average temperature was over 4, not only a single row.
Not sure how to write such query...
One method is:
select s.*
from sensor s
where t > 4 and
not exists (select 1
from sensor s2
where s2.datetime >= s.datetime and
s2.datetime < s.datetime + interval 1 hour and
s2.t <= 4
);
EDIT:
Arggh. The question asks about the average temperature, not any temperature (the question is quite clear, I just misread it).
Here is a variation to handle that:
select s.*,
(select avg(s2.t)
from sensor s2
where s2.datetime >= s.datetime and
s2.datetime < s.datetime + interval 1 hour
) as avg_t
from t
having avg_t > 4;
This uses an extension to MySQL where the having
clause can make use of a column alias for filtering.
Another method is:
SELECT *,
AVG(`t`) AS `avg_t`,
DATE_FORMAT(`date`, '%Y-%m-%d %H') AS `date_and_hour`
FROM `sensor`
GROUP BY DATE_FORMAT(`date`, '%Y-%m-%d %H')
HAVING `avg_t` > 4;
SELECT DATE_FORMAT(DATE_TIME_FIELD, '%Y-%m-%d %H') AS DATE_TIME_HOUR
FROM sensor
GROUP BY DATE_FORMAT(DATE_TIME_FIELD, '%Y-%m-%d %H')
HAVING AVG(T)>4
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.