[英]SQL query over period of time
I have a table in MySQL with some data of a temperature sensor. 我在MySQL中有一个表,其中包含一些温度传感器数据。 I have 1 row per minute.
我每分钟有1排。 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.
我想执行查询以了解是否有1小时的跨度,其中平均温度大于4度。 I know how to perform a query where a single row was above 4:
我知道如何执行单行高于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. 但在我的情况下,我想知道是否存在1小时的平均温度超过4的时间段,而不仅仅是一排。
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. 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. 这使用MySQL的扩展,其中
having
子句可以使用列别名进行过滤。
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.