MySQL查询时间间隔

时间:2017-10-22 15:11:51

标签: mysql sql

我在MySQL中用时间间隔编写一个大查询,现在结果如下:

id       time      comment
=========================== 
1        10:00     start
1        10:10     end
1        14:30     start 
1        15:20     end

但我需要这样做:

id    start_time   end_time
============================
1      10:00        10:10
1      14:30        15:20

我有什么方法可以做到吗?

1 个答案:

答案 0 :(得分:2)

哦,不是微不足道的。这是一种方法:

select id, time as start_time,
       (select t2.time
        from t t2
        where t2.id = t.id and t2.comment = 'end' and t2.time > t.time
        order by t2.time asc
        limit 1
       ) as end_time
from t
where comment = 'start';

这假设开始和结束是完全交错的 - 连续两行都没有。

编辑:

如果数据更复杂,您可以使用变量来排序开始和结束,然后按以下方式汇总:

select id,
       max(case when comment = 'start' then time end) as start_time,
       max(case when comment = 'end' then time end) as end_time
from (select t.*,
             (@s_rn := if(comment = 'start', @s_rn + 1, @s_rn)) as s_rn,
             (@e_rn := if(comment = 'end', @e_rn + 1, @s_rn)) as e_rn
      from t cross join
           (select @s_rn := 0, @e_rn := 0) params
      order by t.time
     ) t
group by id, (case when comment = 'start' then s_rn else e_rn end);