SQL-每个6/7级用户活跃情况

思路

1、生成每个人答题记录2021年活跃天数

2、生成每个人作答记录2021年活跃天数

3、生成每个人2021年活跃天数

4、生成每个人活跃月数

5、过滤条件、连接变量

SELECT ui1.uid,
ifnull(act_month_total,0),
ifnull(act_days_2021,0),
ifnull(act_day_2021_exam,0) ,
ifnull(act_day_2021_question,0)
from user_info as ui1 left join (
 # 生成每个人答题记录2021年活跃天数
select t1.uid,count(distinct t1.year_day)  as act_day_2021_question 
from (
select pr1.uid,DATE_FORMAT(pr1.submit_time,'%Y-%m-%d') as year_day 
    from practice_record as pr1 
where year(pr1.submit_time)='2021' ) t1 group by t1.uid)  a1 
on ui1.uid=a1.uid
left join 
(
 # 生成每个人作答记录2021年活跃天数
select t2.uid,count(distinct t2.year_day)  as act_day_2021_exam 
from (
select pr2.uid,DATE_FORMAT(pr2.start_time,'%Y-%m-%d') as year_day 
    from exam_record as pr2 
where year(pr2.start_time)='2021' ) t2 group by t2.uid) a2
 on ui1.uid=a2.uid
# 生成2021年活跃天数
left join (
select  distinct p4.uid,count(distinct p4.time1) as act_days_2021  
from (
select distinct p1.uid,DATE_FORMAT(p1.submit_time,'%Y-%m-%d') as time1 
from practice_record as p1
UNION all 
select distinct p2.uid,DATE_FORMAT(p2.start_time,'%Y-%m-%d') as time1  
 from exam_record as p2 
) p4 where year(p4.time1)=2021 group by p4.uid
 ) a4 on ui1.uid=a4.uid
# 生成活跃月数
left join (
select distinct p3.uid,count(distinct p3.time1) as act_month_total  
    from (
select distinct p1.uid,DATE_FORMAT(p1.submit_time,'%Y-%m') as time1 
from practice_record as p1
UNION all 
select distinct p2.uid,DATE_FORMAT(p2.start_time,'%Y-%m') as time1 
 from exam_record as p2 ) 
    p3 group by p3.uid) a3 on ui1.uid=a3.uid
  where ui1.level in (6,7) order by act_month_total desc,act_days_2021 desc
备注:变量涉及到两表,由于可能存在重复,因此最好将两张表连接起来并去重,做统计
生成每个人2021年活跃天数、每个人活跃月数的另一种方法
select distinct p3.uid,
    count(distinct date_format(p3.time2,'%Y-%m')) as act_month_total,
    count(distinct if(year(p3.time2)=2021,p3.time2,null)) as act_days_2021
    from (
select distinct p1.uid,DATE_FORMAT(p1.submit_time,'%Y-%m-%d') as time2
from practice_record as p1
UNION all 
select distinct p2.uid,
        DATE_FORMAT(p2.start_time,'%Y-%m-%d') as time2
 from exam_record as p2 ) p3
    group by p3.uid

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值