连续登录天数计算
发表时间:2019-9-24
发布人:葵宇科技
浏览次数:70
最近有个需求,计算用户连续登录的最大天数(这里使用prestoSql,使用hive也可以),先看下登录日志数据表hive.traffic.access_user只有两个字段:uid,day;日期辅助表hive.ods.dim_date,这个表只有一个字段day;
先说下思路,
从上可以看到,只要是连续登录的话,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 alt="在这里插入图片描述" />
end