【问题标题】:Find subscribers who did not resubscribe within threshold of old subscription查找未在旧订阅阈值内重新订阅的订阅者
【发布时间】:2019-04-10 17:28:06
【问题描述】:

我在 PostgreSQL 10.5 中有一个表 Subscriptions:

id  user_id  starts_at  ends_at
--------------------------------
1   233      02/04/19   03/03/19
2   233      03/04/19   04/03/19
3   296      02/09/19   03/08/19
4   126      02/01/19   02/28/19
5   126      03/01/19   03/31/19
6   922      02/22/19   03/22/19
7   111      01/22/19   02/21/19
8   111      02/22/19   03/21/19

我想查看在 3 月订阅结束后 2 天内没有订阅的 user_ids。适用于 3 月结束订阅的用户。

根据上表,结果将是:

user_id
-------
296
126
922
111

我将如何在 3 月份将该查询放在一起?

【问题讨论】:

    标签: sql postgresql date-range


    【解决方案1】:

    不存在应该做你想做的:

    select t.*
    from t
    where ends_at >= '2019-03-01' and ends_at < '2019-04-01' and
          not exists (select 1
                      from t t2
                      where t2.user_id = t.user_id and
                            t2.starts_at >= t.ends_at and
                            t2.starts_at <= t.ends_at + interval '2 day'
                     );
    

    【讨论】:

    • 这很好用,非常感谢。我忘记了我可以将订阅开始/结束日期和 user_id 传递到 not exists 的子选择中。谢谢!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-02-20
    • 1970-01-01
    • 2020-10-17
    • 2020-10-11
    相关资源
    最近更新 更多