0

我有一个表,其中包含以下列“值”列中的数据累积,并且数据以 15 分钟时间间隔获取

name  | value   | start_time          |end_time            |
------------------------------------------------------------
likes | 5       |2013-05-29 16:30:00  |2013-05-29 17:45:00 |
likes | 6       |2013-05-29 17:00:00  |2013-05-29 17:15:00 |
likes | 6       |2013-05-29 17:30:00  |2013-05-29 17:45:00 |
likes | 10      |2013-05-29 18:00:00  |2013-05-29 18:15:00 |
likes | 10      |2013-05-29 18:30:00  |2013-05-29 18:45:00 |
likes | 11      |2013-05-29 19:00:00  |2013-05-29 19:15:00 |
likes | 11      |2013-05-29 19:30:00  |2013-05-29 19:45:00 |

我想要每 1 小时获取一次数据的 sql 查询,并且“值”列中的数据应该是实际数据而不是累积的

例如:

name  | value   | start_time          |end_time            | 
------------------------------------------------------------
likes | 1       |2013-05-29 17:00:00  |2013-05-29 17:59:00 |

或者

name  | value   | start_time          |end_time            | 
------------------------------------------------------------
likes | 1       |2013-05-29 17:00:00  |2013-05-29 17:15:00 |
likes | 0       |2013-05-29 17:30:00  |2013-05-29 17:45:00 |

我希望“价值”列数据作为该时期的实际数据而不是累积数据

4

1 回答 1

0
create table my_test ( `name` char(5), `value` int,  `start_time` datetime, `end_time` datetime);

我已经更正了第一个结束时间,因为我认为这是一个错字( 2013-05-29 17:45:00 到 2013-05-29 17:00:00 ):

insert into my_test values
('likes', 5 ,      '2013-05-29 16:30:00',  '2013-05-29 17:00:00'),
('likes', 6 ,      '2013-05-29 17:00:00',  '2013-05-29 17:15:00'),
('likes', 6 ,      '2013-05-29 17:30:00',  '2013-05-29 17:45:00'),
('likes', 10,      '2013-05-29 18:00:00',  '2013-05-29 18:15:00'),
('likes', 10,      '2013-05-29 18:30:00',  '2013-05-29 18:45:00'),
('likes', 11,      '2013-05-29 19:00:00',  '2013-05-29 19:15:00'),
('likes', 11,      '2013-05-29 19:30:00',  '2013-05-29 19:45:00');

我有一个快速查询,我认为它做了正确的事情,但时间界限有点偏离。

select 'likes' `name`, l2 - l1 `value`, `start`.`start_time` `start_time`,  `end`.`end_time` `end_time`   from
    (
        select date_format(start_time, '%Y-%m-%d %H:00:00') start_time, max(value) l1 from my_test group by date_format(start_time, '%Y%m%d%H')
    ) as `start` join 
    (
        select date_format(start_time, '%Y-%m-%d %H:00:00') end_time, max(value) l2 from my_test group by date_format(start_time, '%Y%m%d%H')
    ) as `end` on `start`.start_time + interval 1 hour = `end`.end_time;

结果如下:

name  | value  | start_time          |end_time              |
------------------------------------------------------------- 
likes | 1      | 2013-05-29 16:00:00 |  2013-05-29 17:00:00 |
likes | 4      | 2013-05-29 17:00:00 |  2013-05-29 18:00:00 |
likes | 1      | 2013-05-29 18:00:00 |  2013-05-29 19:00:00 |
于 2013-06-03T11:31:32.160 回答