SELECT uid, COUNT(DISTINCT DATE_FORMAT(tb.answer_time, '%Y%m')) act_month_total, COUNT( DISTINCT IF( YEAR(tb.answer_time) = 2021, DATE_FORMAT(tb.answer_time, '%Y%m%d'), NULL ) ) act_days_2021, COUNT( DISTINCT IF( YEAR(tb.answer_time) = 2021 AND tag = 'exam', DATE_FORMAT(tb.answer_time, '%Y%m%d'), NULL ) ) act_days_2021_exam, COUNT( DISTINCT IF( YEAR(tb.answer_time) = 2021 AND tag = 'practice', DATE_FORMAT(tb.answer_time, '%Y%m%d'), NULL ) ) act_days_2021_question FROM user_info ui LEFT JOIN ( SELECT uid, start_time answer_time, 'exam' tag FROM exam_record UNION SELECT uid, submit_time answer_time, 'practice' tag FROM practice_record ) tb USING(uid) WHERE ui.level IN (6, 7) GROUP BY uid ORDER BY act_month_total DESC, act_days_2021 DESC;