sql(红移)获取给定列中连续数据的起始值和结束值

d6kp6zgx  于 2021-08-13  发布在  Java
关注(0)|答案(1)|浏览(407)

我有一个表,其中包含用户在任何给定日期的订阅状态。数据是这样的

+------------+------------+--------------+
| 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 窗口函数 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'))
4ioopgfo

4ioopgfo1#

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

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);

相关问题