题解 | #统计复旦用户8月练题情况#
统计复旦用户8月练题情况
https://www.nowcoder.com/practice/53235096538a456b9220fce120c062b3
select
t3.device_id,
t3.university,
count(t3.question_id) as question_cnt,
count(t3.right_question) as right_question_cnt
from
(
select
t1.device_id,
t1.university,
t2.question_id,
t2.result,
case when t2.result = "right" then 'right'
else null
end right_question
from
(
select device_id, university
from user_profile
where university = "复旦大学"
) t1
left join
(
select device_id, question_id, result, `date`
from question_practice_detail
where month(`date`) = 8
) t2
on t1.device_id = t2.device_id
) t3
group by t3.device_id, t3.university
1、查询出复旦大学的用户信息,命名为伪表t1
2、查询出八月份的答题用户,命名为伪表t2
3、连接t1和t2表,left join左查询(要保留所有的用户信息),根据用户id连接,并在这里使用case when语句,增加一列,如果答题为结果正确,就返回"right",否则返回null
4、将第2步骤查出的信息定为t3表,统计根据用户id和学校名称来分组,然后在select中使用count(字段)就可以统计出答题数
count(字段名)不会统计为null的记录,正好可以用它来统计满足需求
