赞
踩
video from https://www.bilibili.com/video/BV1q4411G7Lw?p=9
Student学生表:学号s_id 学生姓名s_name 出生年月 性别
Score 成绩表:学号s_id 课程编号c_id 成绩s_score
Course课程表:课程编号c_id 课程名称c_name 教师号t_id
Teacher 教师表:教师号t_id 教师姓名t_name
一、查询课程编号为01的课程比02的课程成绩高的所有学生的编号(重点)
关键:构成子查询
思路:将学生1课程和2课程的分数分别生成子表
select s_id
(
select s_id, c_id, s_score from score
where c_id = 1
) a
inner join
(
select s_id, c_id, s_score from score
where c_id = 2
) b on a.s_id = b.s_id
where a.s_score > b.s_score
加入学生的分数和名字
加上课程01和02的成绩,并分别命名为01、02
select s_id, a.s_score “01”, b.s_score “02”, c.s_name
(
select s_id, c_id, s_score from score
where c_id = 1
) a
inner join
(
select s_id, c_id, s_score from score
where c_id = 2
) b on a.s_id = b.s_id
where a.s_score > b.s_score
二、查询平均成绩大于60分的学生的学号和平均成绩
关键:group by
select s_id, avg(s_score)
from score
group by s_id
having avg(s_score)>60
做group by时,尽量不要把非group by对象选择到select中,因为意义不大(虽然不会报错)
三、查询所有学生的学号、姓名、选课数、总成绩
思路:选课数用count、总成绩用sum— group by 学生的学号或姓名
学号 姓名 课程编号 这门课的成绩
select a.s_id, a.s_name count(b.c_id), sum(b.s_score)
from
(
select s_id, s_name
from student
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。