结果如下:
level | cn |
忠实用户 | 6 |
新增用户 | 3 |
沉睡用户 | 1 |
需要用到的表:
用户登录明细表:user_login_detail
user_id(用户id) | ip_address(ip地址) | login_ts(登录时间) | logout_ts(登出时间) |
101 | 180.149.130.161 | 2021-09-21 08:00:00 | 2021-09-27 08:30:00 |
102 | 120.245.11.2 | 2021-09-22 09:00:00 | 2021-09-27 09:30:00 |
103 | 27.184.97.3 | 2021-09-23 10:00:00 | 2021-09-27 10:30:00 |
代码:这题题目没有给出今天是哪天,所以代码是没经过测试的
with t as (select user_id ,min(substr(login_ts,1,10)) as frist_login_ts ,max(substr(login_ts,1,10)) as recent_login_ts from user_login_detail group by user_id)select level ,count(user_id) as cn from ( select user_id ,case when (datediff('2023-01-20',recent_login_ts)<=6 and datediff('2023-01-20',frist_login_ts) >6) then '忠实用户'when datediff('2023-01-20',frist_login_ts) <=6 then '新晋用户'when datediff('2023-01-20',recent_login_ts) between 6 and 30 then '沉睡用户' else '流失用户' end as level from t )a group by level
结果如下:
user_id | sum_coin_cn |
101 | 7 |
109 | 3 |
107 | 3 |
102 | 3 |
106 | 2 |
104 | 2 |
103 | 2 |
1010 | 2 |
108 | 1 |
105 | 1 |
需要用到的表:
用户登录明细表:user_login_detail
user_id(用户id) | ip_address(ip地址) | login_ts(登录时间) | logout_ts(登出时间) |
101 | 180.149.130.161 | 2021-09-21 08:00:00 | 2021-09-27 08:30:00 |
102 | 120.245.11.2 | 2021-09-22 09:00:00 | 2021-09-27 09:30:00 |
103 | 27.184.97.3 | 2021-09-23 10:00:00 | 2021-09-27 10:30:00 |
代码
with t as ( select *,count(*) over(partition by user_id, olddate) as lianxudays,count(distinct login_ts) over(partition by user_id )as days from ( select * ,date_add(login_ts,-rn) as olddate from ( select user_id,substr(login_ts,1,10) as login_ts ,row_number() over(partition by user_id order by substr(login_ts,1,10) ) as rn from user_login_detail ) b )a) , t2 as ( select -- 连续签到分二种情况:1、连续超过七天的, 2、未连续超过七天的 ,days ,cast (lianxudays /7 as int )+1 as week_cnt ,case when (lianxudays % 7) < 3 then 0 when (lianxudays % 7) between 3 and 6 then 2 else 8 end external_cnt from t group by user_id ,days ,cast (lianxudays /7 as int )+1 -- 当前第几次7天循环循环 ,case when (lianxudays % 7) < 3 then 0 when (lianxudays % 7) between 3 and 6 then 2 else 8 end )select user_id ,days + external_cnt*week_cnt as sum_coin_cn from ( select user_id ,days ,week_cnt ,sum(external_cnt)as external_cntfrom t2group by user_id ,days ,week_cnt )a