如果它们在相邻小时内,则合并日期

时间:2018-08-02 20:22:27

标签: mysql

我有一个日期和持续时间列表:

-------------------------------------
Date                 |    Duration 
-------------------------------------
2018-08-08 16:00:00  |   00:45:00
2018-08-08 17:00:00  |   00:45:00
2018-08-08 18:00:00  |   00:45:00
2018-08-08 20:00:00  |   00:45:00
-------------------------------------

所需的表输出:

-------------------------------------
Date                 |    Duration 
-------------------------------------
2018-08-08 16:00:00  |   02:45:00
2018-08-08 20:00:00  |   00:45:00
-------------------------------------

有人可以在这个mysql查询中给我提示吗?我的大脑落后了。

Edit1:

我现在将尝试进行选择以匹配相邻查询:

SELECT * FROM appointments WHERE Date BETWEEN ADDTIME(Date, '00:30:00') AND ADDTIME(Date, '01:00:00');

编辑该字段,然后循环查看我是否提取了更多的行。

1 个答案:

答案 0 :(得分:2)

请考虑以下内容...

CREATE TABLE my_table
    (date DATETIME NOT NULL PRIMARY KEY, duration TIME NOT NULL);


INSERT INTO my_table
    (date, duration)
VALUES
    ('2018-08-08 16:00:00', '00:45:00'),
    ('2018-08-08 17:00:00', '00:45:00'),
    ('2018-08-08 18:00:00', '00:45:00'),
    ('2018-08-08 20:00:00', '00:45:00')
;

SELECT MIN(date) date
     , SEC_TO_TIME(SUM(TIME_TO_SEC(duration))) n
  FROM 
     ( SELECT x.*
            , CASE WHEN @prev >= date - INTERVAL 1 HOUR THEN @i := @i ELSE @i:= @i+1 END i
            , @prev := date prev
         FROM my_table x
            , (SELECT @prev := null, @i:=0) vars
        ORDER
           BY date
     ) a
 GROUP 
    BY i;

+---------------------+----------+
| date                | n        |
+---------------------+----------+
| 2018-08-08 16:00:00 | 02:15:00 |
| 2018-08-08 20:00:00 | 00:45:00 |
+---------------------+----------+

http://sqlfiddle.com/#!9/55a1c2c/3