如何编写简明的 sql以按月获取订阅率。
公式:订阅率=订阅计数/试用计数
注意:棘手的部分是订阅事件应该归因于公司开始跟踪的月份.。
| id | date | type |
|-------|------------|-------|
| 10001 | 2019-01-01 | Trial |
| 10001 | 2019-01-15 | Sub |
| 10002 | 2019-01-20 | Trial |
| 10002 | 2019-02-10 | Sub |
| 10003 | 2019-01-01 | Trial |
| 10004 | 2019-02-10 | Trial |
Based on the above table, the out output should be:
2019-01-01 2/3
2019-02-01 0/1发布于 2020-07-18 00:05:01
一种选择是自我连接,以确定每个试验是否最终订阅,然后是聚合和算术:
select
date_trunc('month', t.date) date_month
1.0 * count(s.id) / count(t.id) rate
from mytable t
left join mytable s on s.id = t.id and s.type = 'Sub'
where t.type = 'Trial'
group by date_trunc('month', t.date)将日期截断到本月初的语法因数据库而异。上述工作将在Postgres生效。其他数据库也有替代品,例如:
date_format(t.date, '%Y-%m-01') -- MySQL
trunc(t.date, 'mm') -- Oracle
datefromparts(year(t.date), month(t.date), 1) -- SQL Server发布于 2020-07-18 01:15:50
您可以使用窗口函数来完成这一任务。假设没有重复的审判/分庭:
select date_trunc('month', date) as yyyymm,
count(*) where (num_subs > 0) * 1.0 / count(*)
from (select t.*,
count(*) filter (where type = 'Sub') over (partition by id) as num_subs
from t
) t
where type = 'Trial'
group by yyyymm;如果一个id可以有重复的试验或潜艇,那么我建议你问一个新的问题,更详细的副本。
您还可以通过两个级别的聚合来完成此操作:
select trial_date,
count(sub_date) * 1.0 / count(*)
from (select id, min(date) filter (where type = 'trial') as trial_date,
min(date) filter (where type = 'sub') as sub_date
from t
group by id
) id
group by trial_date;https://stackoverflow.com/questions/62963186
复制相似问题