题解 | #每月及截止当月的答题情况#

一、知识点

聚合窗口函数

二、难点

这道题的难点在于求出每月的新增用户month_add_uv
比如,上个月活跃的用户数有2个,这个月活跃的用户数有3个。这个月中有1个用户在上个月也活跃了,那这个月只有2个新增用户,而不是1个新增用户。

解决思路
引入一列first_month来记录每个用户第一次作答的年月。
然后,我们判断每个月的当前月份 是否= 用户第一次作答的月份 就可以得出来该用户是不是该月的新增用户。使用case语句实现,如果不是,我们就将值设置为null,而count()不会计算null的值。 alt

三、完整代码

select
    start_month,
    mau,
    month_add_uv,
    max(month_add_uv) over (
        order by
            start_month
    ) as max_month_add_uv,
    sum(month_add_uv) over (
        order by
            start_month
    ) as cum_sum_uv
from
    (
        select
            start_month,
            count(distinct uid) as mau,
            count(
                distinct case
                    when start_month = first_month then uid
                    else null
                end
            ) as month_add_uv
        from
            (
                select
                    uid,
                    date_format (start_time, "%Y%m") as start_month,
                    min(date_format (start_time, "%Y%m")) over (
                        partition by
                            uid
                        order by
                            date_format (start_time, "%Y%m")
                    ) as first_month
                from
                    exam_record
            ) t
        group by
            start_month
    ) t
order by
    start_month
全部评论

相关推荐

不知道怎么取名字_:28届都开始出来找机会了,看来哪里都卷
实习简历求拷打
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务