SQL活跃用户等级

:user_login_detail
字段:user_id login_ts

需求:设置活跃用户分级
忠实用户:近7天活跃且非新用户
新晋用户:近7天新增
沉睡用户:近7天未活跃,但7天前活跃

 1 -- 方法一
 2 
 3 select 
 4  user_id,
 5  case 
 6  when first_day between date_sub(date(now()),interval 7 day) and date(now()) then '新晋用户'
 7  when first_day <  date_sub(date(now()),interval 7 day)  and  last_day between date_sub(date(now()),7) and date(now()) then '忠实用户'
 8  else '沉睡用户'
 9  end 用户等级
10  
11  from (
12     select user_id,if(firstd = 1,login_date,null) first_day,if(lastd = 1,login_date,null) last_day
13      
14      from (
15     
16         select user_id,login_date,row_nunber() over(partition by user_id order by login_date) firstd,
17          row_nunber() over(partition by user_id order by login_date desc) lastd 
18          from (
19             select distinct user_id,date(login_ts) login_date from user_login_detail
20         ) a 
21     ) b 
22 ) c 
23 ;
24 
25 
26 -- 方法二
27 
28 
29 select 
30  user_id
31  ,if(min_day >= day_7, '新晋用户',if(max_day >= day_7,'忠实用户','沉睡用户') ) 用户等级
32  
33  
34  from (
35     select 
36      user_id,login_date,max(login_date) over(partition by login_date) max_day
37      ,min(login_date) over(partition by login_date) min_day
38      ,today
39      ,date_sub(today,7) day_7
40      from (
41         select user_id,date_format(login_ts,'yyyy-mm-dd') login_date
42         , date_format(max(login_ts) over(),'yyyy-mm-dd') today from user_login_detail
43     ) a 
44 ) 

 

posted on 2025-06-23 12:00  北京的小乔  阅读(12)  评论(0)    收藏  举报