题解 | #统计复旦用户8月练题情况#
统计复旦用户8月练题情况
https://www.nowcoder.com/practice/53235096538a456b9220fce120c062b3
select up.device_id, university, count(qpd.question_id) question_cnt, sum(if(qpd.result ="right",1,0)) right_question_cnt from user_profile up left join question_practice_detail qpd on up.device_id = qpd.device_id where university = "复旦大学" and (month(qpd.date)= 8 or qpd.date is null) group by up.device_id
一看到这种题还是比较懵的,又是要分组,又是要判断,又要连接,还要进行日期判断
这时候第一步是要仔细读题,先分析可能出现的子句,和要用到的语句。
题目有要求统计没有答过题的用户,所有我们要以user_profile为主表来操作
对于本题来说,实现两表的连接是比较容易实现的,
然后是选择要使用的字段,与本题有关的字段包括,user_profile 的device_id,university ,和 question_practice_detail 的 question_id、result 和 date
先选好五个字段,然后对五个字段进行操作
分析过程
1、用where字段 操作 WHERE t1.university = '复旦大学'
2、时间方面要注意 从题意“8月没有练习过的用户”可知没有答过题的也要统计,
3、但是没有答过题的在左连接下question_id为null 所以要加上
OR t2.date IS NULL
4、result字段是字符型的,题目要求统计回答正确的题数,直接计数肯定不行
所以用case 或者 if 函数转换一下,然后用求和函数统计,可以一并把null和
wrong值转换成0值
5、接下来就是统计题目数,和对答题结果求和
6、最后根据用户分一下组
看解析之前自己写的:
错误点:1.后两列计算函数不够精确;2.month函数里面不用加引号;3.最后应该以up的用户id分组
select
t1.device_id,
t1.university,
count(qpd.question_id) question_cnt,
sum(if(qpd.result ="right",1,0)) right_question_cnt
from
(select
up.device_id,
up.university
from
user_profile up
where month("qpd.date")= 8 ) as t1
left join question_practice_detail qpd
on t1.device_id = qpd.device_id
where t1.university = "复旦大学"
group by qpd.device_id