在MySQL中删除日期时间的重叠

时间:2018-07-05 11:07:21

标签: mysql sql

我有一个表,用于存储登录和注销时间。帮助我消除行之间日期时间的重叠

我有这样的桌子

id | login_time           | logout_time
1  |'2017-02-20 11:20:00' | '2017-02-20 12:10:00'
2  |'2017-02-20 12:13:00' | '2017-02-20 12:40:00'
3  |'2017-02-20 12:30:00' | '2017-02-20 13:10:00'
4  |'2017-02-20 13:20:00' | '2017-02-20 13:30:00'
5  |'2017-02-20 13:25:00' | '2017-02-20 14:20:00'

输出应类似于

login_time           | logout_time
2017-02-20 11:20:00  | 2017-02-20 12:10:00
2017-02-20 12:13:00  | 2017-02-20 13:10:00
2017-02-20 13:20:00  | 2017-02-20 14:20:00

救救我。

2 个答案:

答案 0 :(得分:1)

根据您的输出样本,我更改了查询并检查它返回了您的预期结果集

select t1.logintime,t2.logoutime from
(
select F1.logintime,F1.rank from 
(
select 
  t.logintime,
  CASE WHEN @prevRank = logintime THEN @currRank
       WHEN @prevRank := logintime THEN @currRank := @currRank + 1
   END AS rank
from (
  select  min(login_time) as logintime from time_table
group by hour(login_time) 
  ) t
  cross join (SELECT @currRank := 0, @prevRank := NULL) r

  ) as F1
 ) t1 

inner join

(
select F2.logoutime,F2.rank from
(
select 
  t.logoutime,
  CASE WHEN @preRank = logoutime THEN @curRank
       WHEN @preRank := logoutime THEN @curRank := @curRank + 1
   END AS rank
from (
  select  min(logout_time) as logoutime from time_table
group by hour(logout_time) 
  ) t
  cross join (SELECT @curRank := 0, @preRank := NULL) r

  ) F2
  ) as  t2

  on t1.rank = t2.rank

答案 1 :(得分:0)

与“存在”相关的子查询应该可以解决您的问题

select login_time,logout_time 
from time_table TT1
where not exists 
(
select 1
from time_table TT2
where TT1.login_time  >= TT2.login_time AND 
TT1.login_time <=TT2.logout_time and tt1.id > tt2.id ) 

SQl小提琴link