解体解答SQL150

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

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

第一步,判断每个分数所属区间

            select u1.uid,level,exam_id,score,case when score >= 90 then '优'
                                                        when score < 90 && score >= 75 then '良'
                                                        when score < 75 && score >= 60 then '中'
                                                        else '差' end score_grade
                    from user_info u1 join exam_record e1
                    on u1.uid = e1.uid
                    where score is not null 

第二步,求得每个level,每个score_grade相应的数量

        select level,score_grade,count(*) ct from (
            select u1.uid,level,exam_id,score,case when score >= 90 then '优'
                                                        when score < 90 && score >= 75 then '良'
                                                        when score < 75 && score >= 60 then '中'
                                                        else '差' end score_grade
                    from user_info u1 join exam_record e1
                    on u1.uid = e1.uid
                    where score is not null 
        )t1
        group by level,score_grade

第三步,求得每个level一共多少数量

    select level,score_grade,ct,sum(ct) over(partition by level) sum_ct from(
        select level,score_grade,count(*) ct from (
            select u1.uid,level,exam_id,score,case when score >= 90 then '优'
                                                        when score < 90 && score >= 75 then '良'
                                                        when score < 75 && score >= 60 then '中'
                                                        else '差' end score_grade
                    from user_info u1 join exam_record e1
                    on u1.uid = e1.uid
                    where score is not null 
        )t1
        group by level,score_grade
    )t2

第四步,用第二步求得数量除第三步的数量

select level,score_grade,round(ct/sum_ct,3) ratio from(
    select level,score_grade,ct,sum(ct) over(partition by level) sum_ct from(
        select level,score_grade,count(*) ct from (
            select u1.uid,level,exam_id,score,case when score >= 90 then '优'
                                                        when score < 90 && score >= 75 then '良'
                                                        when score < 75 && score >= 60 then '中'
                                                        else '差' end score_grade
                    from user_info u1 join exam_record e1
                    on u1.uid = e1.uid
                    where score is not null 
        )t1
        group by level,score_grade
    )t2
)t3
order by level desc ,ratio desc

全部评论

相关推荐

03-18 09:45
莆田学院 golang
牛客749342647号:佬,你这个简历模板是哪个,好好看
点赞 评论 收藏
分享
03-31 18:02
门头沟学院 Java
白日梦想家_等打包版:不要的哦佛给我
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客企业服务