题解 | #各用户等级的不同得分表现占比#
各用户等级的不同得分表现占比
https://www.nowcoder.com/practice/ebff819fd38c46db8a42dfe43ca7b33a
题目信息:
- 将试卷得分按分界点[90,75,60]分为优良中差四个得分等级(分界点划分到左区间)
- 统计不同用户等级的人在完成过的试卷中各得分等级占比(结果保留3位小数),未完成过试卷的用户无需输出
解题思路:
- 第一步:首先筛选出用户等级、过滤未完成过试卷的记录:使用join...using(uid)连接
select u.level from exam_record e join user_info u using(uid) where e.score is not null
- 第二步:将不同得分等级:case when 来搞定
case when e.score<60 then '差' when e.score>=60 and e.score<75 then '中' when e.score>=75 and e.score<90 then '良' else '优' end
- 第三步:题目要求按用户等级和得分等级分组,结合第一步和第二步:group by运用
select u.level, case when e.score<60 then '差' when e.score>=60 and e.score<75 then '中' when e.score>=75 and e.score<90 then '良' else '优' end from exam_record e join user_info u using(uid) where e.score is not null group by u.level, case when e.score<60 then '差' when e.score>=60 and e.score<75 then '中' when e.score>=75 and e.score<90 then '良' else '优' end
- 第四步:在用户等级和得分等级不同分组下,求得分数:count(*)
这里需要敲黑板!!!
不知道该咋解释这个窗口函数的使用,只对level分组这里就没有累计的效果,理解为按level对得分等级数的求和吧
- 第五步:求比率:count(*)/sum(count(*)) over(partition by u.level),然后再注意小数点和排序就完事了
select u.level, case when e.score<60 then '差' when e.score>=60 and e.score<75 then '中' when e.score>=75 and e.score<90 then '良' else '优' end,round(count(*)/sum(count(*)) over(partition by u.level),3) ratio from exam_record e join user_info u using(uid) where e.score is not null group by u.level, case when e.score<60 then '差' when e.score>=60 and e.score<75 then '中' when e.score>=75 and e.score<90 then '良' else '优' end order by level desc,ratio desc