有一个表A,请使用SQL找出所有根据user_code重复,且open_time与close_time存在重复的数据,如果close_time为空则默认为关闭时间无穷大。
Id | user_code | … | open_time | close_time |
1 | A | 2019-01-01 | 2019-12-31 | |
2 | B | 2019-02-01 | ||
3 | C | 2019-02-03 | 2019-12-31 | |
… | ||||
100 | A | 2020-01-01 | ||
101 | C | 2018-01-01 | 2020-12-31 | |
… | ||||
200 | A | 2020-06-01 | ||
201 | B | 2019-06-01 | 2020-12-31 | |
… |
例如上表中的数据,第1行与100、200行虽然user_code重复,但时间不重叠,不应该被查出来;100行与200行user_code重复,且open_time与close_time存在重叠;3行与101行的存在重叠应该被查出来;2行与201行时间存在重叠应该查出来。
select distinct
a.*
from
A as a inner join A as b
on a.user_code=b.user_code
where
(a.open_time<b.open_time and b.close_time<a.close_time)
or
(b.open_time<a.open_time and b.close_time<a.close_time)
or
(b.open_time<a.open_time and a.close_time<b.close_time)
or
(a.open_time<b.open_time and b.close_time<a.close_time)
or
(a.open_time<b.open_time and a.close_time is null)
or
(b.open_time<a.open_time and b.close_time is null)
order by a.user_code;