【问题标题】:SQL (Redshift) get start and end values for consecutive data in a given columnSQL (Redshift) 获取给定列中连续数据的开始值和结束值
【发布时间】:2020-05-29 21:50:34
【问题描述】:

我有一张表,其中包含用户在任何一天的订阅状态。数据是这样的

+------------+------------+--------------+
| account_id |    date    | current_plan |
+------------+------------+--------------+
| 1          | 2019-08-01 | free         |
| 1          | 2019-08-02 | free         |
| 1          | 2019-08-03 | yearly       |
| 1          | 2019-08-04 | yearly       |
| 1          | 2019-08-05 | yearly       |
| ...        |            |              |
| 1          | 2020-08-02 | yearly       |
| 1          | 2020-08-03 | free         |
| 2          | 2019-08-01 | monthly      |
| 2          | 2019-08-02 | monthly      |
| ...        |            |              |
| 2          | 2019-08-31 | monthly      |
| 2          | 2019-09-01 | free         |
| ...        |            |              |
| 2          | 2019-11-26 | free         |
| 2          | 2019-11-27 | monthly      |
| ...        |            |              |
| 2          | 2019-12-27 | monthly      |
| 2          | 2019-12-28 | free         |
+------------+------------+--------------+

我想要一个表格,提供订阅的开始和结束日期。它看起来像这样:

+------------+------------+------------+-------------------+
| account_id | start_date |  end_date  | subscription_type |
+------------+------------+------------+-------------------+
|          1 | 2019-08-03 | 2020-08-02 | yearly            |
|          2 | 2019-08-01 | 2019-08-31 | monthly           |
|          2 | 2019-11-27 | 2019-12-27 | monthly           |
+------------+------------+------------+-------------------+

我开始使用LAG windown 函数和一堆WHERE 语句来获取“状态更改”,但这使得很难看到客户何时进出订阅,我不确定这是最好的方法。

lag as (
    select *, LAG(tier) OVER (PARTITION BY account_id ORDER BY date ASC) AS previous_plan
            , LAG(date) OVER (PARTITION BY account_id ORDER BY date ASC) AS previous_plan_date
    from data
)
SELECT *
FROM lag
where (current_plan = 'free' and previous_plan in ('monthly', 'yearly'))

【问题讨论】:

    标签: sql amazon-redshift window-functions


    【解决方案1】:

    这是一个孤岛问题。我认为行号的不同是有效的:

    select account_id, current_plan, min(date), max(date)
    from (select d.*,
                 row_number() over (partition by account_id order by date) as seqnum,
                 row_number() over (partition by account_id, current_plan order by date) as seqnum_2
          from data
         ) d
    where current_plan <> free
    group by account_id, current_plan, (seqnum - seqnum_2);
    

    【讨论】:

    • 所以这非常接近我正在寻找的内容,但它的订阅尚未结束(并且用户进入免费)截至今天。例如,一周前开始订阅的人有一​​行,他们的所有行都显示“每月”,但他们有一个结束日期,即使他们的订阅还没有结束。另外,感谢您为我提供此类问题的正确术语
    • 我想改写一下,我只想看到订阅后进入“免费”的人的开始和结束行
    • @metersk 。 . .这回答了您在这里提出的问题。如果您有不同的问题,则应将其作为新问题提出。
    猜你喜欢
    • 2017-01-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-03-13
    • 1970-01-01
    相关资源
    最近更新 更多