明确题意:

找到每个人近三个有试卷作答记录的月份中没有试卷是未完成状态的用户的试卷作答完成数; 按试卷完成数和用户ID降序排名


问题分解:

  • 统计每人每次试卷作答记录的月份排名,生成子表 t_exam_record_month_rank:
    • 生成当次作答的月份排名,按用户ID分区按年月排序进行窗口连续排名:
      • DENSE_RANK() OVER(PARTITION BY uid ORDER BY DATE_FORMAT(start_time, "%Y%m") DESC) as start_month_rank
  • 筛选月份排名小于等于3的记录(每个人近三个月的):WHERE start_month_rank <= 3
  • 按用户ID分组:GROUP BY uid
  • 筛选都完成了的分组(无未完成试卷):HAVING COUNT(1) = COUNT(score)

细节问题:

  • 表头重命名:as
  • 按试卷完成数和用户ID降序排序:ORDER BY exam_complete_cnt DESC, uid DESC

完整代码:

SELECT uid, COUNT(score) as exam_complete_cnt -- 此人完成的总试卷数
FROM (
    SELECT uid, score,
        DENSE_RANK() OVER(
            PARTITION BY uid
            ORDER BY DATE_FORMAT(start_time, "%Y%m") DESC
        ) as start_month_rank -- 按作答月份降序编号
    FROM exam_record
) as t_exam_record_month_rank
WHERE start_month_rank <= 3
GROUP BY uid
HAVING COUNT(1) = COUNT(score) -- 都完成了
ORDER BY exam_complete_cnt DESC, uid DESC;