题解 | #统计复旦用户8月练题情况#

统计复旦用户8月练题情况

https://www.nowcoder.com/practice/53235096538a456b9220fce120c062b3

select
a.device_id
,'复旦大学' as university
,count(b.question_id) as question_cnt
,sum(if(b.result = 'right',1,0)) as right_question_cnt
from
(select
device_id
from
user_profile
where university = '复旦大学') a
left join
question_practice_detail b
on a.device_id = b.device_id
and date_format(b.date,'%Y-%m') = '2021-08'
group by a.device_id

思路:首先筛选出所有复旦大学的device_id,再左连接question_practice_detail(因为存在有的id当月没有答题的情况,则右表无记录);筛选出8月份数据;再按照Id分组,

问题数量 = 组内question_id之和,count(question_id);

注意:不能为count(*),因为对于学生8月未答题的情况,该条行数据中的question_id为null,count(question_id)会忽略空值,不计数;但是count(*)会记录所有行数为1,结果错误。

正确数量 = 将所有result为right的赋值为1求和。sum(if(b.result = 'right',1,0));

注意:不能用count(b.result='right'),因为count会对所有非空的计数,即使判断为false。

全部评论

相关推荐

评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务