需要在日期期间计算行数,然后根据使用其他条件的日期期间计算行数

时间:2016-12-12 21:36:51

标签: sql postgresql amazon-redshift

我正在尝试计算订阅流失。我有一个如下所示的表:

    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

基本上,此处的目标是查找在给定月份结束的订阅数量,并计算在该月份仍处于活动状态的订阅数量。我不知道如何在同一组中执行此操作,因为第二个计数(id)是以第一个为条件的。

示例表行的结果如下:

date      | count1 | count2
10/1/2016 | 2      | 4
11/1/2016 | 1      | 3
12/1/2016 | 2      | 3 

1 个答案:

答案 0 :(得分:2)

您可以使用相关的子查询来获取不同的计数。

select distinct
date_trunc('month',enddate) as mnth,
(select count(*) from table1 
 where date_trunc('month',enddate) = date_trunc('month',t1.enddate)) count1,
(select count(*) from table1 
 where date_trunc('month',enddate) >= date_trunc('month',t1.enddate) 
 and date_trunc('month',startdate) <= date_trunc('month',t1.enddate)) count2 
from table1 t1
order by 1

另一种方式是自我加入。

select 
date_trunc('month',t1.enddate) as mnth,
count(distinct t1.subid) c1,
count(distinct t2.subid) c2
from table1 t1
left join table1 t2 on date_trunc('month',t2.enddate)>= date_trunc('month',t1.enddate) and date_trunc('month',t2.startdate)<= date_trunc('month',t1.enddate)
group by date_trunc('month',t1.enddate)
order by 1 

<强> Sample Demo

相关问题