【问题标题】:Rolling distinct count 30 day滚动不同计数 30 天
【发布时间】:2020-11-17 09:08:50
【问题描述】:

我需要从 AWS Athena 转换此事件跟踪器数据集

timestamp      id     event
1577863551     1      home
1577863555     1      profile
1577863555     2      home

到每月活跃用户或从 30 天前到现在活跃的唯一用户。例如

date        MAU
2/1/2020    2000
2/2/2020    2500

2000 MAU 表示从 2020 年 1 月 3 日到 2020 年 2 月 1 日,有 2000 个活跃的唯一用户。
2500 MAU 意味着从 2020 年 1 月 4 日到 2020 年 2 月 2 日,有 2500 个活跃的唯一用户

【问题讨论】:

    标签: sql presto amazon-athena


    【解决方案1】:

    这是相当复杂的。 count(distinct) over简单得多!但这就是想法。

    您希望在计算用户时获得时间段。这个想法是生成一个user_inc,当用户开始计数时为1,当用户停止计数时为-1

    但这并不容易计算。这个想法是为用户开始计数和停止计数时添加行(通过添加 31 天)——这些时间段的标志为 1 和 -1`。然后累积总和确定用户在该日期是否有活动。过滤获取活动期间的第一行和最后一行。

    所以,这看起来像:

    with t as (
          select id, dte, sum(sum(inc)) over (partition by id order by dte) as running_ins
          from ((select id, date(from_unixtime(timestamp)) as dte, 1 as inc
                 from event_tracker
                ) union all
                (select id, date(from_unixtime(timestamp)) + interval '31' day as dte, -1 as inc
                 from event_tracker
                )
               ) id
          group by id, dte
         ),
         first_last as (
          select id, dte, (case when running_ins > 0 then 1 else -1 end) as user_inc
          from (select t.*,
                       lag(running_ins) over (partition by id order by dte) as prev_running_ins
                from t
               ) t
          where prev_running_ins is null or
                prev_running_ins = 0 and running_ins > 0 or
                prev_running_ins > 0 and running_ins = 0
         )
    select fl.dte,
           sum(sum(user_inc)) over (order by fl.dte) as distinct_30_days
    from first_last fl
    group by fl.dte;
    

    Here 是一个使用 Postgres 的数据库小提琴。

    【讨论】:

    • 我有这个问题:第 15:89 行:在输入“(滞后(running_ins)超过(按 dte 的 user_id 排序)作为”的情况下(服务:amazonathena;状态代码: 400;错误代码:invalidrequestexception;请求ID:55a759d7-c38c-425e-9da1-1f49b3b384aa)
    • @OctavianWR 。 . .有多个错别字。我修复了这些问题并使用 Postgres 添加了一个小提琴来说明这个想法。注意:只有原始数据中的日期(加上 ate + 31 天)才会在结果集中,因此示例结果不是很有趣。
    • SYNTAX_ERROR: line 23:8: '"sum"("user_inc") OVER (ORDER BY "fl"."dte" ASC)' 必须是聚合表达式或出现在 GROUP BY 子句中
    • @OctavianWR 。 . .我从小提琴中抄错了查询。
    猜你喜欢
    • 2020-11-30
    • 1970-01-01
    • 2021-08-25
    • 1970-01-01
    • 1970-01-01
    • 2018-01-25
    • 2021-08-20
    • 2021-07-08
    • 1970-01-01
    相关资源
    最近更新 更多