题解 | #各用户等级的不同得分表现占比#

各用户等级的不同得分表现占比

http://www.nowcoder.com/practice/ebff819fd38c46db8a42dfe43ca7b33a

SQL41 各用户等级的不同得分表现占比

题目主要信息:

  • 将试卷得分按分界点[90,75,60]分为优良中差四个得分等级(分界点划分到左区间)
  • 统计不同用户等级的人在完成过的试卷中各得分等级占比(结果保留3位小数),未完成过试卷的用户无需输出

问题拆分:

  • 首先筛选出用户ID、相应的完成的考试的ID及其分数、用户等级、分数等级等信息:
    • 上述信息分布在表 user_info和表exam_record中,因此要依靠uid将两张表连接在一起。知识点:join...on...
    • 筛选出题目完成的所有试卷,即有得分的试卷。知识点:where
    • 用户ID、对应的试卷ID、分数、用户等级可由表中直接获取。
    • 设置case根据得分的区间,赋予score_grade优良中差四种字符串。case when score >= 90 then '优' when score >= 75 then '良'when score >= 60 then '中' else '差' end as score_grade 知识点:case when...then...end
    • 统计每个用户等级的总人数。count(*) over(partition by level) as total count()表示统计总数,over表示从此个开始,partition表示以用户等级为划分。 知识点:count、over()、partition by
    • 筛选出的结果记为user_grade_table
  • 从user_grade_table表中筛选出用户等级、成绩等级、相应成绩等级在这个用户等级中的百分比:
    • 要选出每个成绩等级在用户等级中的百分比,我们要以level和score_grade分组。知识点:group by
    • 统计每个组的用户数除以该用户等级的总人数得到比值,取三位小数。round(count(uid) / total, 3) as ratio 知识点:round()、count()
  • 按照先用户等级后比值的降序输出。order by desc

代码:

select level, score_grade, 
       round(count(uid) / total, 3) as ratio
from (
    select u_i.uid as uid,
           exam_id, score, level,
           case when score >= 90 then '优'
                when score >= 75 then '良'
                when score >= 60 then '中'
                else '差' end as score_grade,
           count(*) over(partition by level) as total
    from user_info u_i join exam_record e_r
    on u_i.uid = e_r.uid
    where score is not null 
) user_grade_table
group by level, score_grade
order by level desc, ratio desc


孤帆远影碧空尽 文章被收录于专栏

牛客网各类题单题解~

全部评论
大佬,我想请问一下为什么我的代码里面就第十行的count(*)变成count(score)之后就会有only full group by的报错呀
4 回复 分享
发布于 2022-01-28 14:27
大佬, 您好. 问一下round(count(uid) / total, 3) 这部分, 不是已经根据level, score_grade分组了么? 在select中为什么还能直接使用total列.
4 回复 分享
发布于 2021-11-26 15:43
count(*),可以直接计算group by 里的level ,把count(*) 改成count(level) ,也是可以的。 或者count(score),改成 group by level,total, score_grade 也可以,就不会报错了。
1 回复 分享
发布于 2022-11-30 14:38 北京
请教一下,在分区函数里面:partition by uid。和level有什么区别吗?用uid分组的时候测试用例还会多一条,没有明白
1 回复 分享
发布于 2022-04-21 14:13
感覺round(count(score_grade) / total, 3) as ratio 比較好理解
点赞 回复 分享
发布于 2023-10-08 15:58 广东

相关推荐

11-28 16:13
门头沟学院 Java
程序员小白条:年底了,都差不多了
点赞 评论 收藏
分享
评论
33
4
分享

创作者周榜

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