一段时间的SQL查询

时间:2017-05-29 13:23:01

标签: mysql sql average

我在MySQL中有一个表,其中包含一些温度传感器数据。我每分钟有1排。我想执行查询以了解是否有1小时的跨度,其中平均温度大于4度。我知道如何执行单行高于4的查询:

@Bean
public IntegrationFlow advised() {
    return f -> f.handle((GenericHandler<String>) (payload, headers) -> {
        if (payload.equals("good")) {
            return null;
        }
        else {
            throw new RuntimeException("some failure");
        }
    }, c -> c.advice(expressionAdvice()));
}

@Bean
public Advice expressionAdvice() {
    ExpressionEvaluatingRequestHandlerAdvice advice = new ExpressionEvaluatingRequestHandlerAdvice();
    advice.setSuccessChannelName("success.input");
    advice.setOnSuccessExpressionString("payload + ' was successful'");
    advice.setFailureChannelName("failure.input");
    advice.setOnFailureExpressionString(
            "payload + ' was bad, with reason: ' + #exception.cause.message");
    advice.setTrapException(true);
    return advice;
}

@Bean
public IntegrationFlow success() {
    return f -> f.handle(System.out::println);
}

@Bean
public IntegrationFlow failure() {
    return f -> f.handle(System.out::println);
}

但在我的情况下,我想知道是否有1小时的时间段,平均温度超过4,而不仅仅是一排。

不确定如何编写此类查询...

3 个答案:

答案 0 :(得分:3)

一种方法是:

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

编辑:

Arggh。问题是关于平均温度,而不是任何温度(问题很清楚,我只是误读了它)。

以下是处理该问题的变体:

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;

这使用MySQL的扩展,其中having子句可以使用列别名进行过滤。

答案 1 :(得分:1)

另一种方法是:

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;

答案 2 :(得分:1)

RestItemReader