50个SQL语句(MySQL版) 问题二十二
--------------------------表结构--------------------------
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;
答案仅供参考,不一定完全正确,若发现错误或有更好的,欢迎评论,互相交流,一起成长!!!