首页 > 编程学习 > 连续登录天数计算

连续登录天数计算

发布时间:2022/2/7 9:33:47

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

uiddayrownumberday-rownumber【days】
10120190911120190911-1=20190910
10120190912220190912-2=20190910
10120190913320190913-3=20190910
10120190916420190916-4=20190912
10120190917520190917-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

Copyright © 2010-2022 ngui.cc 版权所有 |关于我们| 联系方式| 豫B2-20100000