mysql - 将表中的两个时间范围合并为一个

标签 mysql sql database

我的 mysql 数据库的可用性表中有以下两列。比如说,它有以下数据。

userid  start     end    date
   2    08:00   09:00   2018-06-20
   2    09:00   16:00   2018-06-20
   2    18:00   21:00   2018-06-20
   2    10:00   02:00   2018-06-21 
..
..

现在,我需要用户每天可用的连续时间范围,例如从 8:00 到 16:00,然后从 18:00 到 21:00。我怎样才能做到这一点?这可以在 mysql 查询本身中完成吗?如果没有的话我该怎么做呢?

最终结果:

userid  start     end    date
   2    08:00   16:00   2018-06-20   [Combined two rows]
   2    18:00   21:00   2018-06-20
   2    10:00   02:00   2018-06-21 

我搜索了很多东西,但没有找到任何答案。请帮助我并告诉我如何做到这一点。

最佳答案

这是一种方法:

-- sample data
create table t (
   userid integer,
   start varchar(5),
   end varchar(5),
   date date
);

insert into t values 
(2, '08:00', '09:00', '2018-06-20'),
(2, '09:00', '16:00', '2018-06-20'),
(2, '18:00', '21:00', '2018-06-20'),
(2, '10:00', '02:00', '2018-06-21');

-- query:
select t1.userid, 
       min(t1.start) start, 
       coalesce(t2.end, t1.end) end, 
       t1.date
  from t t1 left join t t2 
             on    t1.userid=t2.userid 
             and t1.end = t2.start 
             and t1.date = t2.date
group by t1.userid, coalesce(t2.end, t1.end), t1.date
order by t1.userid, t1.date, start;

在这里查看它的工作情况:http://www.sqlfiddle.com/#!9/674fa/1

关于mysql - 将表中的两个时间范围合并为一个,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50948030/

相关文章:

php - htaccess 重写 - 文件名无法识别

php - 通过 MySQL 生成的下拉列表预览 MySQL 中的数据

sql - 在 SQL 中建模用户和角色的正确方法

php - 如何在 PHP 中通过 CheckBox 填充数据库单元格是或否?

database - 如何存储数据的变更历史?

database - 协调器节点及其对性能的影响

php - fatal error : Uncaught exception 'Zend_Exception' with message 'No entry is registered for key ' Zend_Db''

mysql - Slick FRM 中 SQL 的 NOW()

java - byte[] 存储在 Oracle 中

MySQL 对具有条件的列进行行求和