连续登录天数计算

最近有个需求,计算用户连续登录的最大天数(这里使用prestoSql,使用hive也可以),先看下登录日志数据表hive.traffic.access_user只有两个字段:uid,day;日期辅助表hive.ods.dim_date,这个表只有一个字段day;
先说下思路,

uid day rownumber day-rownumber【days】
101 20190911 1 20190911-1=20190910
101 20190912 2 20190912-2=20190910
101 20190913 3 20190913-3=20190910
101 20190916 4 20190916-4=20190912
101 20190917 5 20190917-5=20190912

从上可以看到,只要是连续登录的话,day-rownumber的差值是一样的,那问题来了,这样的减法在跨月或者跨年的时候会出问题,所以我们首先将日期转换成有序的数字

select day,ROW_NUMBER() OVER(ORDER BY day) daynum from hive.ods.dim_date

在这里插入图片描述
接下来,我们需要将用户登录日志按照uid分组,然后按照日期排序,然后计算出rownumber

with a as (select uid,day from hive.traffic.access_user where day>=20190801 and uid<>'')
select uid,day,ROW_NUMBER() OVER(PARTITION BY uid ORDER BY uid,day) rownum from a group by day,uid

在这里插入图片描述
接下来就是计算差值,差值相同的代表连续登录日期,完整sql如下

with a as (select uid,day from hive.traffic.access_user where day>=20190801 and uid<>''),
b as (select uid,day,ROW_NUMBER() OVER(PARTITION BY uid ORDER BY uid,day) rownum from a group by day,uid ),
c as(select day,ROW_NUMBER() OVER(ORDER BY day) daynum from hive.ods.dim_date),
d as (select uid,b.day,daynum,rownum,daynum-rownum days from b join c on b.day=c.day )
select uid,min(day)"连续登录开始日",count(*) "连续登录天数" from d group by uid,days

在这里插入图片描述
end

©️2020 CSDN 皮肤主题: 书香水墨 设计师: CSDN官方博客 返回首页
实付0元
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、C币套餐、付费专栏及课程。

余额充值