题解 | #最长连续登录天数#

最长连续登录天数

https://www.nowcoder.com/practice/cb8bc687046e4d32ad38de62c48ad79b

with
    tmp as (
        select
            user_id,
            fdate,
            lag (fdate, 1, "0000-00-00") over (
                partition by
                    user_id
                order by
                    fdate
            ) fadte_sub
        from
            tb_dau
        where
            fdate between "2023-01-01" and "2023-01-31"
    ) #使用lag 窗口函数,按用户id分组,登陆日期升序,进行日期偏移,
    tmp2 as (
        select
            user_id,
            fdate,
            fadte_sub,
            datediff (fdate, fadte_sub) as diff_date,
            if (datediff (fdate, fadte_sub) < 2, "0", fdate) as dt_line
        from
            tmp
    ) # 登陆日期和偏移日期作差,如果日期差小于2(连续日期差为1,间隔一天算连续日期差为2,其余以此类推),则为连续登录,记作0,否则为当前登录日期。,
    tmp3 as (
        select
            *,
            max(dt_line) over (
                partition by
                    user_id
                order by
                    fdate
            ) as max_dt_line
        from
            tmp2
    ) # 利用窗口函数max,将连续登录的日期修正成起始登录日期
select
    user_id,
    max(consec_days) as max_consec_days
from
    (
        select
            user_id,
            max_dt_line,
            count(*) as consec_days
        from
            tmp3
        group by
            user_id,
            max_dt_line
    ) tmp4
group by
    user_id # 根据起始登录日期分组找到最大值

全部评论

相关推荐

微风不断:兄弟,你把四旋翼都做出来了那个挺难的吧
点赞 评论 收藏
分享
无情咸鱼王的秋招日记之薛定谔的Offer:好拒信,偷了,希望有机会用到
点赞 评论 收藏
分享
1 收藏 评论
分享
牛客网
牛客企业服务