简体   繁体   English

查找订阅日期重叠的用户

[英]find users with overlapping subscription dates

I have a subscription 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

I am looking to get the list of users with overlapping subscription with ANY of the other users.我正在寻找与任何其他用户重叠订阅的用户列表。

user_id overlap
1   True
2   True
3   True
4   False

I tried this:我试过这个:

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

but it gives me following results:但它给了我以下结果:

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

I am thinking that you can use exists :我在想你可以使用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 is a db<>fiddle. 是一个 db<>fiddle。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM