题解 | 统计复旦用户8月练题情况
统计复旦用户8月练题情况
https://www.nowcoder.com/practice/53235096538a456b9220fce120c062b3
发现一个有趣的问题,如果把 if(result = 'right' ,1,0) 放在t2子表中,结果会报错,在8月没有答题过的学生,他的正确回复返回的是 null。为什么呢?看完代码后,往下看
select t1.device_id,t1.university,count(question_id) as question_cnt ,
sum(if(result = 'right' ,1,0)) as right_question_cnt
from
(select device_id,university
from user_profile
where university = '复旦大学'
)t1
left join
(select result,date,
device_id,question_id
from question_practice_detail
)t2
on t1.device_id = t2.device_id and month(t2.date) = 8
group by university,device_id
当 IF 放在 t2 子表中时,8 月没答题的学生在 t2 中无记录,导致 is_right 为 NULL,SUM(NULL) 结果为 NULL。
当 IF 放在主查询中时,8 月没答题的学生 t2.result 为 NULL,IF 函数会将其转为 0,SUM(0) 结果为 0。
踩坑了,记录以下
查看10道真题和解析
小天才公司福利 1311人发布