明确题意:
找到昵称以『牛客』开头『号』结尾、成就值在1200~2500之间且最近一次活跃(答题或作答试卷)在2021年9月的用户信息
问题分解:
- 筛选用户条件:
- 昵称以『牛客』开头『号』结尾:WHERE nick_name LIKE "牛客%号"
- 成就值在1200~2500之间:achievement BETWEEN 1200 AND 2500
- 最近一次活跃(答题或作答试卷)在2021年9月:
- 生成用户每次活跃月份:
- 试卷区活跃情况:SELECT distinct uid, DATE_FORMAT(start_time, "%Y%m") as active_month
- 练习区活跃情况:SELECT distinct uid, DATE_FORMAT(submit_time, "%Y%m") as active_month
- 合并活跃情况:UNION
- 按用户分组:GROUP BY uid
- 筛选最近一次活跃月份:HAVING MAX(active_month)="202109"
- 生成用户每次活跃月份:
细节问题:
- 表头重命名:as
完整代码:
SELECT uid, nick_name, achievement
FROM user_info
WHERE nick_name LIKE "牛客%号" and achievement BETWEEN 1200 AND 2500 AND uid IN (
SELECT uid
FROM (
SELECT distinct uid, DATE_FORMAT(start_time, "%Y%m") as active_month
FROM exam_record
UNION
SELECT distinct uid, DATE_FORMAT(submit_time, "%Y%m") as active_month
FROM practice_record
) as t_uid_active_month
GROUP BY uid
HAVING MAX(active_month)="202109"
);