1. 程式人生 > 其它 >mysql統計各部門人數_mysql case when 案例:統計各科成績各分數段人數所佔百分比...

mysql統計各部門人數_mysql case when 案例:統計各科成績各分數段人數所佔百分比...

技術標籤:mysql統計各部門人數統計不及格人數pta

表資訊

成績表score

96ebb7e8aa6bb6241dfa65994718d763.png

課程表course

7009c8a07fdecabd9748dd1de84cdc77.png

-- 統計各科成績各分數段人數:課程編號,課程名稱,(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;

1064d4db8055cd99cd5b3bd05c008298.png