明确题意:

筛选出试卷作答数小于3的类别tag,统计将其转换为大写后对应的原本试卷作答数。

如果转换后tag并没有发生变化,不输出该条结果。


问题分解:

  • 统计每类试卷的作答数(区分大小写),生成临时表 t_tag_count:
    • 左连接试卷作答表和试卷信息表:exam_record LEFT JOIN examination_info USING(exam_id)
    • 按试卷类别分组:GROUP BY tag
    • 统计每类试卷作答数:SELECT tag, COUNT(uid) as answer_cnt
  • 对表t_tag_count进行自连接,假设取出的两条记录分别为a和b:t_tag_count as a JOIN t_tag_count as b
  • 选出满足题目条件的结果:
    • a.tag转大写后和b.tag一样:ON UPPER(a.tag) = b.tag
    • a.tag转换后必须发生变化:a.tag != b.tag
    • a的试卷作答数小于3:a.answer_cnt < 3

细节问题:

  • 表头重命名:as

完整代码:

WITH t_tag_count as (
    SELECT tag, COUNT(uid) as answer_cnt
    FROM exam_record
    LEFT JOIN examination_info USING(exam_id)
    GROUP BY tag
)

SELECT a.tag, b.answer_cnt
FROM t_tag_count as a
JOIN t_tag_count as b
ON UPPER(a.tag) = b.tag and a.tag != b.tag and a.answer_cnt < 3;