1

我有一个跟踪用户活动的表(即用户在什么时间开始会话?)。此表包含 2018 年 12 月至今的数据。我需要根据用户活动(即 2018 年 12 月,有 500 名用户活跃。然后,他们中有多少人在 1 月、2 月、3 月......直到现在?相同活动应在 2019 年 1 月、2019 年 2 月执行......直到现在用户)。

我尝试了硬编码的方式,即让2018 年 12 月的用户进入表,然后在其他表中获取 2019 年 1 月的用户,并根据 user_ids 加入两个表,但为此我必须编写很多连接. 需要一种动态方法来检查月度用户保留率以及 2018 年 12 月之后的所有月份(因为数据从本月开始可用)。

select A.year_month_id,count(distinct A.user_id) as November_Users,count(distinct B.user_id) as December_Retained_Users 
FROM (
        select date_trunc('month', ua.created_at) as monthly,
        ua.user AS user_id
        FROM     user_activity ua
        WHERE    ua.event_type='StartSession'
        and     cast(ua.created_at as date) between cast('20181201' as date) and cast('20181231' as date)
        GROUP BY 1,2
    ) AS A
left Join 
    (
        select date_trunc('month', ua.created_at) as monthly,
        ua.user AS user_id
        FROM     user_activity ua
        WHERE    ua.event_type='StartSession'
        and     cast(ua.created_at as date) between cast('20190101' as date) and cast('20190131' as date)
        GROUP BY 1,2
    ) AS B 
on A.user_id=B.user_id
group by 1

user_activity 表#

id | user | event_type   | created_at
1  | A1   | StartSession | April 29, 2019, 3:59 AM
2  | A2   | StartSession | December 29, 2018, 1:07 AM
3  | A3   | StartSession | December 9, 2018, 4:59 PM
49 | A31  | StartSession | May 25, 2019, 11:59 AM
100| A46  | StartSession | April 29, 2019, 3:56 AM

预期输出#

Month |Monthly_Active_Users| Jan_Retained|Feb_Retained|Mar_Retained|.......
Dec   | 500                |  300        |  200       | 330
Jan   | 700                |  N/A        |  450       | 410
Feb   | 1000               |  N/A        |  N/A       | 820
Mar   | 920                |  N/A        |  N/A       | N/A
.
.
.
.
Aug   | 100                | N/A         |    N/A     | N/A
4

1 回答 1

0

我认为这将完成这项工作:

with t as (
    select distinct user_, to_char(created_at, 'yymm') dt
      from user_activity where event_type = 'StartSession'),
  u as (
    select a.user_, a.dt mth, b.dt dt, count(distinct a.user_) over (partition by a.dt) cnt
      from t a join t b on (a.user_ = b.user_ and b.dt >= a.dt))
select * from u pivot (count(user_) for dt in (1901, 1902, 1903, 1904)) order by mth

dbfiddle 演示

我假设该列created_atdate数据类型。如果没有,请使用演员表,无论对您有用。我们需要在查询中将此值转换为yymm. 也是user保留字,我user_在查询中使用。

in将所有月份 (1901...1908)填写在 pivot 子句中的列表中,并在未来添加下个月。Pivot 不允许在这里使用动态语法,您必须指定它们。

这个怎么运作:

首先 - 表中的不同值(用户、月份)。然后是最重要的部分——自我加入,它为每个用户创建开始月份和未来月份的元组。此外,我在这里添加了分析计数,这是您报告中第二列所必需的。最终支点只是聚合这些准备好的数据。

于 2019-08-08T11:54:58.190 回答