题解 | 统计复旦用户8月练题情况 (sum(if)函数和对null的处理)
统计复旦用户8月练题情况
https://www.nowcoder.com/practice/53235096538a456b9220fce120c062b3
select
t1.device_id,
t1.university,
count(t2.device_id) as question_cnt,
sum(if(t2.result='right',1,0)) as right_question_cnt
from
user_profile t1
left join
question_practice_detail t2
on t1.device_id=t2.device_id and month(t2.date)=8
where t1.university='复旦大学'
group by t1.device_id,t1.university
--因为用到了查询字段和聚合函数在一起,所以必须用group by
--month的判断必须放在on的位置,因为只有这样才会有null,count的时候自动会数成0