with t as (select level,score,count(level)over(partition by level) as level_cn, (case when score<60 then '差' when score<75 and score>=60 then '中' when score<90 and score>=75 then '良' else '优' end) as grade from exam_record left join user_info using(uid) where score is not null) select level,grade,round(count(level)/level_cn,3) as ratio from t group by level,grade order by level desc,ratio desc