中午小时观察

时间:2013-09-03 15:57:31

标签: mysql datetime

我有一个包含多行的表,如下所示:

+---------------------+------+
| 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的类型为datetimetemp的类型为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。)

1 个答案:

答案 0 :(得分:1)

我会使用存储过程:

delimiter $$
create procedure get_temps(d0 date, d1 date)
begin
    declare d date;
    declare done tinyint default 0;
    declare cur_dates cursor for
        select distinct date(utc) as date 
        from `table`
        where date(utc) between d0 and d1;
    declare continue handler for not found
        set done = 1;
    -- Create a table to store the data
    create table if not exists tbl_temp_data (
        utc datetime,
        temp int
    );

    open cur_dates;
    temp_filter: while done=0 do
        fetch cur_dates into d;
        if done = 0 then
            insert into tbl_temp_data
            SELECT 
                utc, temp 
            FROM 
                `table` 
            WHERE 
                DATE(utc)=d
            ORDER BY 
                ABS(TIMESTAMPDIFF(SECOND,utc,DATE_ADD(DATE(utc),INTERVAL 12 HOUR))) 
            LIMIT 1;

        end if;
    end while;
end $$
delimiter ;