本系列同样是记录代码为主,附带实验内容与要求,可参考代码,SQL编码习惯为小写且习惯性换行。
实验的环境和软件为Microsoft SQLServer 2019。
实验内容:
1.查询所有选课学生的姓名、课程名和成绩。
--3-3-1
select sname,cname,grade
from student,course,sc
where student.sno=sc.sno and course.cno=sc.cno
2.列出选修了“数学”或者“大学英语”的学生的学号、姓名、课程名、成绩。
--3-3-2
select x.sno,sname,cname,grade
from student x,course y,sc z
where x.sno=z.sno and y.cno=z.cno and (cname='数学' or cname='大学英语')
3.查询选修课程有1门以上与李勇选修课程相同的学生的学号、课程号。
select sno,cno
from sc
where cno in (
select cno from sc where sno in (
select sno from student where sname='李勇'))
4.列出各班的班级编号、班级名称、学生人数。
--3-3-4
select a.clno,a.clname,sum(case when a.clno=b.clno then 1 else 0 end) as 'samount'
from class a,student b
group by a.clno,a.clname
5.列出各门课程的课程号、课程名、平均成绩。
--3-3-5
select a.cno,cname,avg(b.grade) as 'avg_grade'
from course a,sc b
where a.cno=b.cno
group by a.cno,cname
6.列出只选修了1门课程的学生的学号、姓名。
--3-3-6
select sno,sname
from student
where sno in (
select sno from sc group by sno having count(*)=1)
7.查询只有1名学生选修的课程的课程号、课程名。
--3-3-7
select cno,cname
from course
where cno in(
select cno from sc group by cno having count(*)=1)
8.采用集合运算查询同时选修了“数据库”和“数据结构”的学生的学号、姓名。
--3-3-8
select sno,sname
from student
where sno in (
select sno from sc where cno in (
select cno from course where cname='数据库'))
intersect
select sno,sname
from student
where sno in(
select sno from sc where cno in (
select cno from course where cname='数据结构'))
9.列出只选修了“数据库”和“数据结构”两门课程的学生的学号、姓名。
--3-3-9
select sno,sname
from student
where sno in (
select sno from sc where cno in (
select cno from course where cname='数据库' and cname='数据结构'
group by cno having count(*)=2))
10.列出没有选修 “数据结构”课程的学生的学号、姓名。
--3-3-10
select sno,sname
from student
except
select sno,sname
from student
where sno in (
select sno from sc where cno in (
select cno from course where cname='数据结构'))