SQL数据查询实例1

现在有三张表:

  • 学生表Student(Sno, Sname)
  • 课程表Course(Cno, Cname)
  • 选课表Student_Course(Sno, Cno, Grade)

数据库实例如下:
数据库实例

要求用SQL语句检索:
1)  选修语文的学生姓名

select S.Sno,Sname
from Student as S,Course as C,Student_Course as SC
where S.Sno=SC.Sno and C.Cno=SC.Cno and C.Cname='语文'

2)  至少选修了语文和数学的学生姓名

select S.Sno,Sname
from Student_Course as SC1,Course as C1,
     Student_Course as SC2,Course as C2,
     Student as S     
where SC1.Cno=C1.Cno and SC2.Cno=C2.Cno
      and SC1.Sno=SC2.Sno and SC1.Sno=S.Sno  
      and C1.Cname='语文' and C2.Cname='数学'

3)  只选修了语文和数学的学生姓名

select S.Sno,S.Sname
from Student_Course as SC,Student as S
where SC.Sno=S.Sno and S.Sno in(select S.Sno 
                                from Student_Course as SC1,Course as C1,
                                     Student_Course as SC2,Course as C2,
                                     Student as S     
                                where SC1.Cno=C1.Cno and SC2.Cno=C2.Cno
                                      and S.Sno=SC1.Sno and SC1.Sno=SC2.Sno
                                      and C1.Cname='语文' and C2.Cname='数学')
group by S.Sno,S.Sname
Having Count(S.Sno)=2

4)  每个学生的平均分

select S.Sno,S.Sname,AVG(Grade) as '平均分'
from Student as S,Student_Course as SC
where S.Sno=SC.Sno
group by S.Sno,S.Sname;

5)  各门课程平均分高于70分的学生姓名

select S.Sno,S.Sname,AVG(Grade) as '平均分'
from Student as S,Student_Course as SC
where S.Sno=SC.Sno
group by S.Sno,S.Sname
Having AVG(Grade)>70

6)  学生平均分高于70分的课程名称

select C.Cno,C.Cname,AVG(Grade) as '平均分'
from Course as C,Student_Course as SC
where C.Cno=SC.Cno
group by C.Cno,C.Cname
Having AVG(Grade)>70

7)  各门课程平均分高于李四的学生姓名

SELECT sc.Sno, s.Sname, avg( Grade ) as '平均分'
FROM student_course AS sc, student AS s
WHERE sc.Sno = s.Sno
GROUP BY sc.Sno,Sname
Having avg(Grade)>(Select avg(Grade) 
                    from student_course AS sc,student AS s
                    where sc.Sno=s.Sno and s.Sname='李四');

8)  可以准予毕业的学生姓名(至少选了2门课,每门课的成绩不低于60分)

SELECT sc.Sno, s.Sname
FROM student_course AS sc, student AS s
WHERE sc.Sno = s.Sno and S.Sno in (select distinct S.Sno
                                    from Student_Course as SC1,
                                         Student_Course as SC2,
                                         Student as S     
                                    where SC1.Sno=SC2.Sno and SC1.Sno=S.Sno  
                                          and SC1.Cno<>SC2.Cno)
GROUP BY sc.Sno,Sname
Having MIN(Grade)>=60
原文地址:https://www.cnblogs.com/emituofo/p/2774811.html