题解 | #每个6/7级用户活跃情况#
每个6/7级用户活跃情况
http://www.nowcoder.com/practice/a32c7c8590324c96950417c57fa6ecd1
##解析题目
1、因为要求总活跃月份数,所以需要把试卷表和问题记录表上下拼接,用到union all函数,这个地方要求两个表格的字段名称必须一致,所以我们可以把两个表格中重要的信息提取出来设定成相同的字段,就可以进行拼接了:
select uid, start_time act_time from exam_record
union all
select uid, submit_time act_time from practice_record
union all
select uid, submit_time act_time from practice_record
2、2021年的总活跃天数,只要在1中加入一个年份等于2021的条件就好了:
select uid, start_time act_time from exam_record
union all
select uid, submit_time act_time from practice_record)g
where year(act_time)=2021
select uid, submit_time act_time from practice_record)g
where year(act_time)=2021
3、2021年的试卷回答记录:之所以用了一个左连接,是要保证那些没有做过试卷的人有一个null值,不至于选不出uid,但是好像在最开始已经有一个6/7级大佬的uid了。
select a.uid, s.act_days_2021_exam n2
from user_info a
left join
(select uid, count(distinct date(start_time))act_days_2021_exam
from exam_record
where year(start_time)=2021
group by uid
)s using(uid))m3 using(uid)
from user_info a
left join
(select uid, count(distinct date(start_time))act_days_2021_exam
from exam_record
where year(start_time)=2021
group by uid
)s using(uid))m3 using(uid)
4、2021年的问题回答记录:好像也不用左连接...
select uid,r.n3 from user_info
left join(select uid,
count(distinct date(submit_time)) n3
from practice_record
where year(submit_time)=2021
group by uid)r using(uid)
left join(select uid,
count(distinct date(submit_time)) n3
from practice_record
where year(submit_time)=2021
group by uid)r using(uid)
##将以上满足要求的表格选出来之后,按顺序与6/77级大佬的uid进行左连接就好了,也就是最开头部分
select m.uid,
if(m1.s1 is null,0,m1.s1) act_month_total,if(m2.s2 is null,0,m2.s2) act_days_2021,
if(m3.n2 is null,0,m3.n2) act_days_2021_exam,
if(m4.n3 is null,0,m4.n3) act_days_2021_question
from
(select uid from user_info
where `level` = 6 or `level` = 7)m left join
先写最后一部分,然后按顺序1234左连接即可,别忘记排序。