整到一張表:
select 課程,
sum(人數*case 類別 when "優秀" then 1 else 0 end) 優秀人數,sum(人數*case 類別 when "優秀" then 1 else 0 end)/sum(人數)*100 優秀百分比,
sum(人數*case 類別 when "良好" then 1 else 0 end) 良好人數,sum(人數*case 類別 when "良好" then 1 else 0 end)/sum(人數)*100 良好百分比,
sum(人數*case 類別 when "中等" then 1 else 0 end) 中等人數,sum(人數*case 類別 when "中等" then 1 else 0 end)/sum(人數)*100 中等百分比,
sum(人數*case 類別 when "及格" then 1 else 0 end) 及格人數,sum(人數*case 類別 when "及格" then 1 else 0 end)/sum(人數)*100 及格百分比,
sum(人數*case 類別 when "缺考" then 1 else 0 end) 缺考人數,
sum(人數*case 類別 when "不及格" then 1 else 0 end) 不及格人數,
sum(人數*case when 類別 in("優秀","良好","中等","及格") then 1 else 0 end) 及格人數
from (select 課程,count(*) as 人數,‘優秀’ as 類別
from 成績
where grade>=90
group by 課程
union
select 課程,count(*) as 人數,‘良好’ as 類別
where grade>80 and grade
select 課程,count(*) as 人數,‘中等" as 類別
where grade>70 and grade
select 課程,count(*) as 人數,‘及格’ as 類別
where grade>=60 and grade
select 課程,count(*) as 人數,‘不及格’ as 類別
where grade
select 課程,count(*) as 人數,‘缺考" as 類別
where grade is null
group by 課程)
group by 課程 ;
整到一張表:
select 課程,
sum(人數*case 類別 when "優秀" then 1 else 0 end) 優秀人數,sum(人數*case 類別 when "優秀" then 1 else 0 end)/sum(人數)*100 優秀百分比,
sum(人數*case 類別 when "良好" then 1 else 0 end) 良好人數,sum(人數*case 類別 when "良好" then 1 else 0 end)/sum(人數)*100 良好百分比,
sum(人數*case 類別 when "中等" then 1 else 0 end) 中等人數,sum(人數*case 類別 when "中等" then 1 else 0 end)/sum(人數)*100 中等百分比,
sum(人數*case 類別 when "及格" then 1 else 0 end) 及格人數,sum(人數*case 類別 when "及格" then 1 else 0 end)/sum(人數)*100 及格百分比,
sum(人數*case 類別 when "缺考" then 1 else 0 end) 缺考人數,
sum(人數*case 類別 when "不及格" then 1 else 0 end) 不及格人數,
sum(人數*case when 類別 in("優秀","良好","中等","及格") then 1 else 0 end) 及格人數
from (select 課程,count(*) as 人數,‘優秀’ as 類別
from 成績
where grade>=90
group by 課程
union
select 課程,count(*) as 人數,‘良好’ as 類別
from 成績
where grade>80 and grade
group by 課程
union
select 課程,count(*) as 人數,‘中等" as 類別
from 成績
where grade>70 and grade
group by 課程
union
select 課程,count(*) as 人數,‘及格’ as 類別
from 成績
where grade>=60 and grade
group by 課程
union
select 課程,count(*) as 人數,‘不及格’ as 類別
from 成績
where grade
group by 課程
union
select 課程,count(*) as 人數,‘缺考" as 類別
from 成績
where grade is null
group by 課程)
group by 課程 ;