在MySQL中我有一个表node_weather:
mysql> desc node_weather;
+--------------------+--------------+------+-----+-------------------+-----------------------------+
| Field | Type | Null | Key | Default | Extra |
+--------------------+--------------+------+-----+-------------------+-----------------------------+
| W_id | mediumint(9) | NO | PRI | NULL | auto_increment |
| temperature | int(10) | YES | | NULL | |
| humidity | int(10) | YES | | NULL | |
| time | timestamp | NO | | CURRENT_TIMESTAMP | on update CURRENT_TIMESTAMP |
现在我需要做的是:当天每两个小时(00:00:00,02:00:00,...,24:00:00)我想得到一个温度。通常查询可能是这样的:
mysql> SELECT temperature
-> FROM node_weather
-> WHERE date(time) = DATE(NOW())
-> AND TIME(time) IN ('00:00:00','02:00:00','04:00:00','06:00:00','08:00:00','10:00:00','12:00:00','14:00:00','16:00:00','18:00:00','20:00:00','22:00:00','24:00:00');
在理想的情况下,我应该得到一个结果,选择了12行,一切都会好的。但它有两个问题:
我知道这有点尴尬,但这就是我老板想要的。感谢帮助!
答案 0 :(得分:0)
好的,比我在评论中写的更精确:
编辑:有一个错误。希望这不会。
SELECT
time,
deviation,
hour,
temperature
FROM (
SELECT
time,
ROUND(HOUR(time) / 2) * 2 AS hour,
IF(HOUR(time) % 2,
3600 - MINUTE(time) * 60 - SECOND(time),
MINUTE(time) * 60 + SECOND(time)
) AS deviation,
temperature
FROM node_weather
WHERE DATE(time) = DATE(NOW())
ORDER BY deviation ASC
) t
GROUP BY hour
ORDER BY
hour ASC
基本上,按照09:00:00 - 10:59:59(通过舍入小时/ 2)的间隔进行分组,然后按这些间隔按升序排序,并在间隔内按距离中心的距离排序(所以我们在09:00:00或10:59:59选择10:00:00。