1. 程式人生 > 其它 >查詢各科成績最高分、最低分和平均分(case when then else end)

查詢各科成績最高分、最低分和平均分(case when then else end)

技術標籤:SQL server 筆記sqlmysqlsqlserver

資料,建立表,檢視資料表(程式碼)~

1、查詢各科成績最高分、最低分和平均分:

要求:

– 以如下形式顯示:課程 ID,課程 name,最高分,最低分,平均分,及格率,中等率,優良率,優秀率
– 及格為>=60,中等為:70-80,優良為:80-90,優秀為:>=90
– 要求輸出課程號和選修人數,查詢結果按人數降序排列,若人數相同,按課程號升序排列

select Course.C#,Course.Cname,A.最高分,A.最低分,A.平均分,B.及格率,C.中等率,D.優良率,E.優秀率,F.選修人數
from
Course left join (select C#, max(score) 最高分,min(score) 最低分,AVG(score) 平均分 from SC group by C# )A on Course.C# = A.C# left join (select C#, (convert( decimal(5,2),( sum (case when score >= 60 then 1 else 0 end)*1.00 /count(*) ) )*100) 及格率 from SC group by C#)B on Course.C# = B.C# left join (select C#,
(convert( decimal(5,2),( sum (case when score >=70 and score<80 then 1 else 0 end)*1.00 /count(*) ) )*100) 中等率 from SC group by C#)C on Course.C# = C.C# left join (select C#, (convert( decimal(5,2),( sum (case when score >=80 and score<90 then 1 else 0 end)*1.00 /count(*) ) )*100) 優良率 from SC group by
C#)D on Course.C# = D.C# left join (select C#, (convert( decimal(5,2),( sum (case when score >=90 then 1 else 0 end)*1.00 /count(*) ) )*100) 優秀率 from SC group by C#)E on Course.C# = E.C# left join (select C#,count(S#) 選修人數 from SC group by C#)F on Course.C# = F.C# order by F.選修人數 desc,Course.C# asc


在這裡插入圖片描述

2、統計各科成績各分數段人數:課程編號,課程名稱,[100-85],[85-70],[70-60],[60-0] 及所佔百分比

select Course.C#,Course.Cname,A.[100-85],A.所佔百分比 ,
 B.[85-70],B.所佔百分比 , C.[70-60],C.所佔百分比 , D.[60-0],D.所佔百分比 from Course 
left join (select C#,sum (case when score >85  then 1 else 0 end) [100-85],
(convert( decimal(5,2),( sum (case when score >85  then 1 else 0 end)*1.00 /count(*) ) )*100) 所佔百分比 
from SC group by C#)A on Course.C# = A.C#
left join (select C#,sum (case when score >70 and score<=85 then 1 else 0 end) [85-70],
(convert( decimal(5,2),( sum (case when score >70 and score<=85 then 1 else 0 end)*1.00 /count(*) ) )*100) 所佔百分比 
from SC group by C#)B on Course.C# = B.C#
left join (select C#,sum (case when score >60 and score<=70 then 1 else 0 end) [70-60],
(convert( decimal(5,2),( sum (case when score >60 and score<=70 then 1 else 0 end)*1.00 /count(*) ) )*100) 所佔百分比 
from SC group by C#)C on Course.C# = C.C#
left join (select C#,sum (case when score <= 60 then 1 else 0 end) [60-0],
(convert( decimal(5,2),( sum (case when  score <= 60 then 1 else 0 end)*1.00 /count(*) ) )*100) 所佔百分比 
from SC group by C#)D on Course.C# = D.C#


在這裡插入圖片描述