三个步骤: ①准备aa表:把试卷表和问题表union,通过uid来分组,后面用于计算活跃的月份和天数; ②准备bb表:user_info表选出6/7级的uid,后面用来与aa表连接,为的是把从未活跃过的uid也放到总表里; ③筛选计算:试卷组别(900开头)、问题组别(800开头)、年份2021 可作为count内部if筛选条件。 select uid, count(distinct date_format(b,'%Y%m')) act_month_total, count(distinct if(year(b)=2021,date_format(b,'%Y%m%d'),null)) act_days_2021, count(distinct if(a>9000 and year(b)=2021,date_format(b,'%Y%m%d'),null)) act_days_2021_exam, count(distinct if(a<9000 and year(b)=2021,date_format(b,'%Y%m%d'),null)) act_days_2021_question from ( select uid, exam_id a, start_time b from exam_record union all select uid, question_id a, submit_time b from practice_record) as aa right join (select uid from user_info where level in (6,7)) as bb using(uid) group by uid order by act_month_total desc, act_days_2021 desc