【发布时间】:2016-12-12 21:36:50
【问题描述】:
我正在尝试计算订阅流失率。我有一个如下所示的表:
subid | startdate | enddate
000001 | 9/26/2016 | 10/26/2016
000002 | 11/4/2015 | 12/4/2016
000003 | 11/18/2016| 12/18/2016
000004 | 8/3/2016 | 10/16/2016
000005 | 7/16/2016 | 11/29/2016
要按月计算流失率,我需要创建如下所示的逻辑:
select
date_trunc('month',enddate) as month,
count(id), --of all accounts with an enddate of that month
count(id), --of all accounts that have a start date prior to that month and an end date equal to or after that month
from table1
这里的主要目标是找出在给定月份结束的订阅数量,并计算该月仍然有效的订阅数量。我不知道如何在同一组中执行此操作,因为第二个 count(id) 以第一个为条件。
示例表行的结果是这样的:
date | count1 | count2
10/1/2016 | 2 | 4
11/1/2016 | 1 | 3
12/1/2016 | 2 | 3
【问题讨论】:
-
使用条件聚合
sum(case when ... then 1 else 0 end ) as cnt2 -
@xQbert 感谢您的想法,但由于该行的结束日期是 count(id) 而对 count2 而言,这将是实际与行无关的数据吗?
-
可能类似于 ..
sum(case when startDate < date_trunc('month', current_date) and endDate>=date_trunc('month', endDate) - 1 then 1 else 0 end)
标签: sql postgresql amazon-redshift