查找日期范围与其他日期范围发生冲突的记录

时间:2018-01-22 11:07:44

标签: postgresql date overlap date-range

让我们打赌用户想要找到哪个日期范围与给定范围发生冲突的记录:< 2018-01-01; 2018年2月28日>

例如,我们有一个给定的数据集

|--- FROM --- | --- TO --- | ------ COLLIDES ------ |
| 2018-01-01  | 2018-01-05 | YES (with all 5 days)  |
| 2018-01-01  | 2018-01-01 | YES (with 1 day)       |
| 2017-12-20  | 2019-10-19 | YES (with all 5 days)  |
| 2017-12-25  | 2017-12-31 | NO                     |
| 2018-03-01  | 2018-03-20 | NO                     |

是否有有效的方法来过滤给定日期范围碰撞的数据集?

2 个答案:

答案 0 :(得分:0)

完成

select date_from, date_to, (date_from, date_to) 
OVERLAPS(DATE '2018-01-01' - interval '1 day', DATE '2018-02-28' + interval '1 day') 
from test

答案 1 :(得分:0)

just checking

t=# with c(f,t) as (values('2018-01-01'::date,'2018-01-05'::date))
select daterange(f,t,'()') && '(2018-01-01, 2018-02-28)'::daterange from c;
 ?column?
----------
 t
(1 row)

and the intersection value:

t=# with c(f,t) as (values('2018-01-01'::date,'2018-01-05'::date))
select daterange(f,t,'()') * '(2018-01-01, 2018-02-28)'::daterange from c;
        ?column?
-------------------------
 [2018-01-02,2018-01-05)
(1 row)