查找订阅日期重叠的用户

问题描述 投票:0回答:2

我有一个订阅表:

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
sql postgresql case
2个回答
0
投票

我想你可以使用

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;

这里是一个db<>小提琴。


0
投票
        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
group by u1.user_id
order by u1.user_id;```
© www.soinside.com 2019 - 2024. All rights reserved.