mysql統計各部門人數_mysql case when 案例:統計各科成績各分數段人數所佔百分比...
阿新 • • 發佈:2020-12-10
表資訊
成績表score
課程表course
-- 統計各科成績各分數段人數:課程編號,課程名稱,(0-60],(60,70],(70,85],(85,100]所佔百分比
然而這麼寫是不對的~between and 是兩邊閉區間
select score.c_id,c_name, sum(score between 0 and 60)/count(score) 不及格率, sum(score between 60 and 70) 中等率, sum(score between 70 and 85)/count(score) 優良率, sum(score between 85 and 100)/count(score) 優秀率 from score left join course on score.c_id = course.c_id group by score.c_id;
要這麼寫
select score.c_id,c_name, sum(case when 0<score and score<= 60 then 1 else 0 end)/count(score) 不及格率, sum(case when 60<score and score<= 70 then 1 else 0 end)/count(score) 中等率, sum(case when 70<score and score<=85 then 1 else 0 end)/count(score) 優良率, sum(case when 85<score and score<=100 then 1 else 0 end)/count(score) 優秀率 from score left join course on score.c_id = course.c_id group by score.c_id;