这道题一次过。

这题难点在于,最后求和时的有两个取值的时间范围, 第一个结果是不分年。总的活跃月份 后几个结果都是要2021年的值。

步骤一:将题目和测试两个表合并,分别给与一个字段标签。方便后续统计。需要注意上下两表的列数要对齐(看了眼答案,好像不需要像我这样多产生一列临时列) 步骤二:统计数量,这里主要使用的是date_format,从时间字段提取日期。 步骤三:连接用户表,找到6/7级用户。 步骤四:排序

select 
u.uid ,
count(distinct date_format(start_time,'%Y-%m')) act_month_total,
count(distinct if(date_format(start_time,'%Y-%m-%d') and start_time like '2021%',date_format(start_time,'%Y-%m-%d'),null)) act_days_2021,
count(distinct if(date_format(start_time,'%Y-%m-%d') and type = 'exam' and start_time like '2021%',date_format(start_time,'%Y-%m-%d'),null)) act_days_2021_exam ,
count(distinct if(date_format(start_time,'%Y-%m-%d') and type = 'practice' and start_time like '2021%',date_format(start_time,'%Y-%m-%d'),null)) act_days_2021_question
from (
select uid,exam_id,start_time,submit_time,score,'exam' as type from exam_record
union all 
select uid,question_id,submit_time start_time,submit_time,score,'practice' as type from practice_record ) a
right join  user_info u
on a.uid=u.uid 
where level in(6,7)
group by u.uid
order by act_month_total desc, act_days_2021 desc