查找订阅日期重叠的用户

find users with overlapping subscription dates

我订阅了 table:

user_id | start_date | end_date
1         1/1/2019   1/31/2019
2         1/15/2019  1/17/2019
3         1/29/2019  2/4/2019
4         2/5/2019   2/10/2019

我正在寻找与任何其他用户有重叠订阅的用户列表。

user_id overlap
1   True
2   True
3   True
4   False

我试过了:

select  u1.user_id,
        case when u1.end_date > u2.start_date and u1.start_Date < u2.end_date 
        then 'True' 
        else 'False' end as overlap
from subscriptions u1 
join subscriptions u2 
    on u1.user_id <> u2.user_id

但它给了我以下结果:

1   True
1   True
1   False
2   True
2   False
2   False
3   True
3   False
3   False
4   False
4   False
4   False

我认为你可以使用 exists:

select s.*,
       (exists (select 1
                from subscriptions s2
                where s2.start_date < s.end_date and
                      s2.end_date > s.start_date and
                      s2.user_id <> s.user_id
               )
       ) as has_overlap_flag
from subscriptions s;

Here 是一个 db<>fiddle.