明确题意:

统计不同用户等级的人在完成过的试卷中各得分等级占比(结果保留3位小数),未完成过试卷的用户无需输出。

试卷得分按分界点[90,75,60]分为优良中差四个得分等级(分界点划分到左区间)

结果按得分等级降序、占比降序排序。


问题分解:

  • 统计每次试卷完成记录的分数、等级、得分等级和该用户等级总人数,生成子表 t_level_grade:
    • 内连接试卷作答表和用户信息表:exam_record JOIN user_info USING(uid)
    • 筛选已完成作答的记录:WHERE submit_time IS NOT NULL
    • 生成得分等级:CASE WHEN score >= 90 THEN '优' ... END AS score_grade
    • 统计该用户等级总人数,拼接到每条记录:COUNT(score) over(PARTITION BY level) AS level_cnt
  • 按用户等级、得分等级分组:GROUP BY level, score_grade
  • 计算每个得分等级占比:COUNT(score_grade) / level_cnt AS ratio

细节问题:

  • 表头重命名:as
  • 按得分等级降序、占比降序排序:ORDER BY level DESC, ratio DESC

完整代码:

SELECT `level`, score_grade,
    ROUND(COUNT(score_grade) / level_cnt, 3) AS ratio
FROM (
    SELECT
        uid, exam_id, score, `level`,
        CASE
            WHEN score >= 90 THEN '优'
            WHEN score >= 75 THEN '良'
            WHEN score >= 60 THEN '中'
            ELSE '差'
        END AS score_grade,
        COUNT(score) over(PARTITION BY `level`) AS level_cnt
    FROM exam_record JOIN user_info USING(uid)
    WHERE submit_time IS NOT NULL
) AS t_level_grade
GROUP BY `level`, score_grade
ORDER BY `level` DESC, ratio DESC;