sql语句多表联查语句的练习(面试题)

此篇文章中所示用的sql语句适用于mysql关系型数据库查询数据,其他类型的数据库是否支持,没有去尝试,想要在mysql
1.首先准备两个表,一个是学生表(student)
sql语句多表联查语句的练习(面试题)_第1张图片
另一个是科目分数表(grade)
sql语句多表联查语句的练习(面试题)_第2张图片
当数据准备完成后,接下来就开始真正的问题了。
问题一: 列出各门课程成绩最好的2位学生,要求显示字段:学号,姓名,科目,成绩
sql语句多表联查语句的练习(面试题)_第3张图片
查询语句如下所示:select a.id,a.name,a.kemu,a.score from(select s.id,s.name,g.kemu,g.score from student s,grade g where s.id=g.id) as a where(select count(*) from (select s.id,s.name,g.kemu,g.score from student s,grade g where s.id=g.id) as b where b.kemu=a.kemu and b.score >= a.score)<=2 order by a.kemu asc,a.score desc;其中a,b表示的都是结果集。

问题二: 计算每个人的成绩,总分数,平均分,要求显示学号,姓名,语文,数学,英语,总分,平均分

sql语句多表联查语句的练习(面试题)_第4张图片
查询语句如下所示:select s.id,s.name,max(case when g.kemu=‘语文’ then score else 0 end) as 语文,max(case when g.kemu=‘数学’ then score else 0 end) as 数学,max(case when g.kemu=‘英语’ then score else 0 end) as 英语,sum(score) as 总分,avg(score) as 平均分 from student s,grade g where s.id = g.id group by id;

问题三: 列出数学成绩的排名(要求显示字段:学号,姓名,成绩,排名)
注:排序,比较大小,比较的次数+1 = 排名

sql语句多表联查语句的练习(面试题)_第5张图片
select a.id,a.name,a.score,(select count(*) from grade where kemu=‘数学’ and score > a.score)+1 as 名次 from (select s.id,s.name,g.kemu,g.score from student s,grade g where s.id=g.id) as a where a.kemu=‘数学’ order by a.score desc;

下面连接中拥有最详细的步骤从创建数据库开始到问题的解决,有需要点击“学生信息查询”进行下载。
学生信息查询

你可能感兴趣的:(mysql)