我有一个包含许多行的表,如下所示:
+---------------------+------+
| utc | temp |
+---------------------+------+
| 2011-01-30 00:00:14 | -3 |
| 2011-01-30 00:40:06 | -4 |
| 2011-01-30 01:00:15 | -4 |
| 2011-01-30 01:20:14 | -4 |
| 2011-01-30 02:00:12 | -4 |
| 2011-01-30 02:20:18 | -4 |
| 2011-01-30 03:00:16 | -4 |
| ... | ... |
utc
是 类型datetime
,temp
是 类型int
。
对于每一天,我想找到temp
最接近当天中午的值。可能会生成一个如下所示的表:
+---------------------+------+
| utc | temp |
+---------------------+------+
| 2011-01-30 12:01:14 | -3 |
| 2011-01-31 11:58:36 | -4 |
| 2011-02-01 12:00:15 | -5 |
| 2011-02-02 12:03:49 | -7 |
| 2011-02-03 02:00:12 | -8 |
| ... | ... |
在一天之内找到这个很容易:
SELECT utc, temp FROM table WHERE DATE(utc)='2011-01-30' ORDER BY ABS(TIMESTAMPDIFF(SECOND,utc,DATE_ADD(DATE(utc),INTERVAL 12 HOUR))) LIMIT 1;
但不知何故,每天同时做这件事被证明更具挑战性。
(请注意,可能有比temp
表中更多的值。)