查找具有定义结束的连续相同值的行组(SQL红移)
我有一个表,其中包含任何给定日期的用户订阅状态。数据如下所示查找具有定义结束的连续相同值的行组(SQL红移),sql,amazon-redshift,Sql,Amazon Redshift,我有一个表,其中包含任何给定日期的用户订阅状态。数据如下所示 +------------+------------+--------------+ | account_id | date | current_plan | +------------+------------+--------------+ | 1 | 2019-08-01 | free | | 1 | 2019-08-02 | free | | 1
+------------+------------+--------------+
| 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 |
| 3 | 2020-05-31 | monthly |
| 3 | 2020-06-01 | monthly |
| 4 | 2019-08-01 | yearly |
| ... | | |
| 4 | 2020-06-01 | yearly |
+------------+------------+--------------+
我想有一个表格,提供订阅的开始和结束日期。它看起来像这样。请注意,重要的是,此表中不包括帐户ID 3和4,因为截至2020年6月1日,它们仍在订阅中。我只想要一份从订阅中移出的人的摘要
+------------+------------+------------+-------------------+
| 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 |
+------------+------------+------------+-------------------+
目前,我有以下非常接近,但仍然给我的用户没有退出订阅
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
) d
where current_plan not in ('free', 'trial')
group by account_id, current_plan, (seqnum - seqnum_2);
如果您想对截至目前已退出的用户进行非常简单的筛选,只需添加: 有maxdate