首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >SQL月订阅率

SQL月订阅率
EN

Stack Overflow用户
提问于 2020-07-17 23:56:51
回答 2查看 238关注 0票数 1

如何编写简明的 sql以按月获取订阅率。

公式:订阅率=订阅计数/试用计数

注意:棘手的部分是订阅事件应该归因于公司开始跟踪的月份.

代码语言:javascript
复制
| 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
EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2020-07-18 00:05:01

一种选择是自我连接,以确定每个试验是否最终订阅,然后是聚合和算术:

代码语言:javascript
复制
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生效。其他数据库也有替代品,例如:

代码语言:javascript
复制
date_format(t.date, '%Y-%m-01')               -- MySQL
trunc(t.date, 'mm')                           -- Oracle
datefromparts(year(t.date), month(t.date), 1) -- SQL Server
票数 2
EN

Stack Overflow用户

发布于 2020-07-18 01:15:50

您可以使用窗口函数来完成这一任务。假设没有重复的审判/分庭:

代码语言:javascript
复制
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可以有重复的试验或潜艇,那么我建议你问一个新的问题,更详细的副本。

您还可以通过两个级别的聚合来完成此操作:

代码语言:javascript
复制
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;
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/62963186

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档