明确题意:

找到昵称以"牛客"+纯数字+"号"或者纯数字组成的用户对于字母c开头的试卷类别(如C,C++,c#等)的已完成的试卷ID和平均得分,按用户ID、平均分升序排序。


问题分解:

  • 筛选已完成的记录:WHERE score IS NOT NULL
  • 筛选试卷,用正则表达式匹配试卷类型(REGEXP或RLIKE):WHERE tag REGEXP "^[cC]"
  • 筛选用户,用正则表达式匹配昵称:WHERE nick_name REGEXP "^牛客[0-9]+号$" OR nick_name REGEXP "^[0-9]+$"
  • 按用户ID和试卷ID分组:GROUP BY uid, exam_id
  • 计算平均分:AVG(score) as avg_score
  • 保留为整数:ROUND(x, 0)

细节问题:

  • 表头重命名:as
  • 按用户ID、平均分升序排序:ORDER BY uid, avg_score

完整代码:

SELECT uid, exam_id, ROUND(AVG(score), 0) as avg_score
FROM exam_record
WHERE score IS NOT NULL
and exam_id in (
    SELECT exam_id
    FROM examination_info
    WHERE tag REGEXP "^[cC]"
)
and uid in (
    SELECT uid FROM user_info
    WHERE nick_name REGEXP "^牛客[0-9]+号$"
        OR nick_name REGEXP "^[0-9]+$"
)
GROUP BY uid, exam_id
ORDER BY uid, avg_score;