题解 | 统计复旦用户8月练题情况
统计复旦用户8月练题情况
https://www.nowcoder.com/practice/53235096538a456b9220fce120c062b3
select u.device_id, u.university, count(q.result) question_cnt, sum(if(result='right',1,0)) right_question_cnt from user_profile u left join question_practice_detail q on u.device_id =q.device_id and month(q.date)=8 where university='复旦大学' group by u.university,u.device_id
这道题一开始我想用子查询去写,后来发现麻烦了。
1.解释下为什么有的人不显示没有答过题的人的信息(其实这只是我自己的错误)
因为如果你写where university='复旦大学'and month(date)=8,即使是left join 这个时候 没答过题的人的日期自然是null,所以where语句一执行就直接没了
所以这里我们在左连接时指定日期,这样就不会没了。
from user_profile u
left join question_practice_detail q
on u.device_id =q.device_id
and month(q.date)=8
这段代码保留了所有人八月份的数据;
where university='复旦大学'
执行完where就剩下我们要找的所有了
再选自己想要的筛选出来就好了