# 【hive】关于用户留存率的计算

(1)找到这个时间段内的新增用户(也可能含有地区啊的各种附加条件),一般在日活表中有记录是否是新增状态.
注意,需要以天为单位进行分组找出用户的id.因为留存率都是以每天为单位进行计算的.
表结构(register_date,user_id)

(2)找到这个时间段内的活跃用户(active_date,user_id)

(3)以 1表 为主表left join 2表 以user_id为关联键,统计留存数

这样后的记录类型为:register_date,user_id,active_date

register_date为新增日期,即留存率的单位天.

user_id为用户id,distinct user_id来计算用户数

active_date - register_date = 1,说明注册的次日用户是活跃的,所以count+1
所以我们只要关注 active_date 和 register_date 相差天数即可统计留存数
取天数差的时候用datediff(active_date,register_date)来计算,active_date 和 register_date 的格式为 yyyy-MM-dd

(4)计算留存率

    SET mapreduce.job.queuename=xxx;
SET mapreduce.job.name=xxx;
set mapreduce.job.reduces=19;
select '日期', '注册用户数', '次日留存率', '2日留存率', '3日留存率',  dim_date
,total_cnt
,concat_ws('% | ', cast(round(dif_1cnt*100/total_cnt, 2) as string), cast(dif_1cnt as string))
,concat_ws('% | ', cast(round(dif_2cnt*100/total_cnt, 2) as string), cast(dif_2cnt as string))
,concat_ws('% | ', cast(round(dif_3cnt*100/total_cnt, 2) as string), cast(dif_3cnt as string))
,concat_ws('% | ', cast(round(dif_4cnt*100/total_cnt, 2) as string), cast(dif_4cnt as string))
from
(
select p1.state dim_date
,p1.device_os
,count(distinct p1.user_id) total_cnt
,count(distinct if(datediff(p3.state,p1.state) = 1, p1.user_id, null)) dif_1cnt
,count(distinct if(datediff(p3.state,p1.state) = 2, p1.user_id, null)) dif_2cnt
,count(distinct if(datediff(p3.state,p1.state) = 3, p1.user_id, null)) dif_3cnt
,count(distinct if(datediff(p3.state,p1.state) = 4, p1.user_id, null)) dif_4cnt
from
(
select
from_unixtime(unix_timestamp(cast(partition_date as string), 'yyyyMMdd'), 'yyyy-MM-dd') state,
user_id
from user_active_day
where partition_date between date1 and date2
and user_is_new = 1
group by 1,2
)p1 --日新增用户名单(register_date,user_id)
left outer join
(
select
from_unixtime(unix_timestamp(cast(partition_date as string), 'yyyyMMdd'), 'yyyy-MM-dd') state,
user_id
from active_users
where partition_date between date1 and date2
group by 1,2
)p3 --期间活跃用户(active_date,user_id)
on (p3.user_id = p1.user_id)
group by 1,2
) p4;

posted @ 2018-10-31 18:17  zzhangyuhang  阅读(9173)  评论(0编辑  收藏  举报