表結構 student(StuId,StuName,StuAge,StuSex) 學生表 teacher(TId,Tname) 教師表 course(CId,Cname,C_TId) 課程表 sc(SId,S_CId,Score) 成績表 問題二十二:查詢如下課程成績第3名到第6名的學生成績單:企業 ...
--------------------------表結構--------------------------
student(StuId,StuName,StuAge,StuSex) 學生表
teacher(TId,Tname) 教師表
course(CId,Cname,C_TId) 課程表
sc(SId,S_CId,Score) 成績表
----------------------------------------------------------
問題二十二:查詢如下課程成績第3名到第6名的學生成績單:企業管理(001),馬克思(002),UML(003),資料庫(004)格式:[學生ID],[學生姓名],企業管理,馬克思,UML,資料庫,平均成績
SELECT stu.StuId,stu.StuName, BM.Score AS BM,Marx.Score AS Marx,UML.Score AS UML,DB.Score AS DB, (IFNULL(BM.Score,0)+IFNULL(Marx.Score,0)+IFNULL(UML.Score,0)+IFNULL(DB.Score,0))/ (SUM(CASE WHEN IFNULL(BM.Score,0)=0 THEN 0 ELSE 1 END)+ SUM(CASE WHEN IFNULL(Marx.Score,0)=0 THEN 0 ELSE 1 END)+ SUM(CASE WHEN IFNULL(UML.Score,0)=0 THEN 0 ELSE 1 END)+ SUM(CASE WHEN IFNULL(DB.Score,0)=0 THEN 0 ELSE 1 END)) AS AvgScore FROM student stu LEFT JOIN sc AS BM ON BM.SId=stu.StuId AND BM.S_CId='001' LEFT JOIN sc AS Marx ON Marx.SId=stu.StuId AND Marx.S_CId='002' LEFT JOIN sc AS UML ON UML.SId=stu.StuId AND UML.S_CId='003' LEFT JOIN sc AS DB ON DB.SId=stu.StuId AND DB.S_CId='004' GROUP BY stu.StuId ORDER BY AvgScore DESC LIMIT 2,4;
答案僅供參考,不一定完全正確,若發現錯誤或有更好的,歡迎評論,互相交流,一起成長!!!