题解 | #满足条件的用户的试卷完成数和题目练习数#
满足条件的用户的试卷完成数和题目练习数
https://www.nowcoder.com/practice/5c03f761b36046649ee71f05e1ceecbf
SELECT a.uid, a.exam_cnt, COALESCE(b.question_cnt, 0) FROM ( # 试卷完成情况 SELECT uid, COUNT(score) exam_cnt FROM exam_record WHERE YEAR(submit_time) = 2021 GROUP BY uid ) a LEFT JOIN ( # 题目完成情况 SELECT uid, COUNT(if(score, 1, NULL)) question_cnt FROM practice_record WHERE YEAR(submit_time) = 2021 GROUP BY uid ) b ON a.uid = b.uid WHERE a.uid IN (SELECT DISTINCT uid FROM exam_record a JOIN examination_info b USING(exam_id) JOIN user_info c USING(uid) WHERE level = 7 AND tag = 'SQL' AND difficulty = 'hard' GROUP BY uid HAVING AVG(score) > 80) # 用户限制 ORDER BY exam_cnt ASC, question_cnt DESC;
分而治之,先写限制用户的子查询,为什么视图创建显示没有权限呢?
然后针对2021年的情况分别调出试题和练习题情况
再根据“只保留21年有试卷记录的”,所以采用左外联结。
这样带来的问题是有的没有练习题记录,就成了NULL,所以用COALESCE函数
COALESCE
是一个在SQL中广泛使用的函数,它的作用是从其参数列表中返回第一个非NULL
的值。如果所有的参数都是NULL
,那么 COALESCE
函数也会返回NULL
。这个函数非常有用,尤其是在处理可能出现NULL
值的情况时。