SQL每小时​​数据

时间:2012-11-13 18:24:48

标签: mysql sql

下面的查询从MySql数据库中检索天气数据,并将此数据分组为每小时格式。

select hour(datetime) AS hour
     , avg(Temperature) as AVGT 
from Database.minute
WHERE DATETIME
      BETWEEN (CURDATE() + INTERVAL (SELECT hour(NOW())) hour - INTERVAL 23 hour)
         AND ((CURDATE() + INTERVAL (SELECT hour(NOW())) hour))
group by hour
order by  (CURDATE() + INTERVAL (SELECT hour(NOW())) hour - INTERVAL 23 hour)

输出如下:

hour    AVGT
19     11.730
20     11.970
21     11.970
22     11.760
23     11.660
0      11.700
1      11.830
2      12.370
3      12.770
4      12.840
5      12.840
6      12.540
7      12.500
8      12.030
9      12.100
10     12.300
11     12.060
12     11.090
13     10.920
14     10.920
15     10.820
16     10.760
17     10.690
18     10.560

时间现在是18:15。除了为'18'小时收集的数据之外,所有上述输出都是正确的。它不是在18:00到18:15之间获得平均值,而是在18:00时输出平均值。即。在18:01和18:14之间忽略数据。

如何修改上述查询以包含当前小时(18:00至今)的数据?

由于

2 个答案:

答案 0 :(得分:4)

你为什么不试试

SELECT Hour(datetime)   AS hour, 
       Avg(temperature) AS AVGT 
FROM   DATABASE.minute 
WHERE  datetime BETWEEN ( Curdate() + INTERVAL (SELECT Hour(Now())) hour - 
                          INTERVAL 23 hour ) AND Now() 
GROUP  BY hour 
ORDER  BY ( Curdate() + INTERVAL (SELECT Hour(Now())) hour - INTERVAL 23 hour ) 

答案 1 :(得分:3)

我同意@Ankur's answer(你的过滤器citerion不应该过滤记录到当前时间,而是当前时间),但是你的日期/时间操作非常奇怪:

  1. 您不需要子查询(SELECT Hour(NOW()))来获取HOUR(NOW());

  2. 您可以更简单地表达( Curdate() + INTERVAL (SELECT Hour(NOW())) hour - INTERVAL 23 hour )

    CURDATE() + INTERVAL HOUR(NOW()) - 23 HOUR
    

    或者,在我看来,更清楚:

    DATE_FORMAT(NOW() - INTERVAL 23 HOUR, '%Y-%m-%d %H:00:00')
    
  3. 您的ORDER BY子句是一个常数,因此无法实现:您的意思是按hour订购吗?

  4. 因此:

    SELECT   HOUR(datetime) AS hour,
             AVG(Temperature) AS AVGT
    FROM     Database.minute
    WHERE    datetime BETWEEN
                   DATE_FORMAT(NOW() - INTERVAL 23 HOUR, '%Y-%m-%d %H:00:00')
               AND NOW()
    GROUP BY hour
    ORDER BY hour