目录
5、查询选修了3号课程的学生的学号和成绩,其结果按分数的降序排列。
6、查询全体学生的情况,查询结果按所在系升序排列,对同一系中的学生按年龄降序排列。
16、求基本表S中男同学的每一年龄组(超过50人)有多少人?要求查询结果按人数升序排列,人数相同按年龄降序排列。
设教学数据库Education有三个关系:
学生关系S(Sno,Sname, Ssex,Sage,Sdept);
学习关系SC(Sno,Cno,Grade);
课程关系C(Cno,Cname,Cdept,Tname)
查询问题
1、查所年龄在20至23岁之间的学生姓名、系别及年龄。
select Sname,Sdept,Sage
from S
where Sage between 20 and 23
2、查既不是计算机系、数学系、又不是信息系的学生姓名、性别
select Sname,Ssex
From S
Where Sdept not in('CS','MA','IS')
3、查所有姓“刘”的学生的姓名、学号和性别。
select Sname,Sno,Sex
from S
where Sname like "刘%"
4、查缺考的学生的学号和课程号。
select Sno,Cno
from SC
where Grade is null
5、查询选修了3号课程的学生的学号和成绩,其结果按分数的降序排列。
select Sno,Grade
from SC
where Cno='3'
order by Grade desc
6、查询全体学生的情况,查询结果按所在系升序排列,对同一系中的学生按年龄降序排列。
select *
from S
order by Sdept asc,Sage desc
7、查询学生总人数。
select count(*)
from S
8、检索选修课程号为2或4的学生学号;
select Sno
from SC
where Cno='2' or Cno='4'
9、检索至少选修课程号为C2和C4的学生学号;
select Sno
from SC
where Cno='C2' and Sno in
(select Sno
from SC
where Cno='C4')
10、检索不学C2课的学生姓名和年龄;
select Sno,Sage
from S
where Sno not in
(select Sno from SC where Cno='C2')
11、检索学习全部课程的学生姓名;
//Exists子句只返回true值,Not Exists只返回false值。
select Sname
from S
where not exists
(select * from C
where not exists
(select * from SC
where S.Sno=SC.Sno and SC.Cno=C.Cno))
//查找学习了所有课程的学生,即是在C中不存在一门课程没有学。
12、查询所学课程包含学生S3所学课程的学生学号。
select Sno
from SC
where Cno in
(select Cno
from SC
where Sno='S3')
13、计算选修了C1课程的学生平均成绩。
select avg(Grade)
from SC
where Cno='C1'
14、查询各个课程号与相应的选课人数。
select Cno,count(Sno)
from Sc
group by Cno
15、查询计算机系选修了3门以上课程的学生的学号。
select Sno
from S,SC
where Sdept='CS' and S.Sno=SC.Sno
group by Sno
having count(*)>3
16、求基本表S中男同学的每一年龄组(超过50人)有多少人?要求查询结果按人数升序排列,人数相同按年龄降序排列。
select Sage,count(Sno)
from S
group by age
having count(*)>50
order by count(*) asc,Sage desc
17、查询选修了C2课程且成绩在90分以上的所有学生。
select Sno
from SC
where Cno='C2' and Grade>90
18、统计每一年龄选修课程的学生人数。
select Sage,count(distinct S.Sno)
from S,SC
where S.Sno=SC.Sno
group by age
19、查询选修课程名为“数据库”的学生学号和姓名。
//嵌套查询
select Sno,Sname
from S
where Sno in
(select Sno
from SC
where Cno in
(select Cno
from C
where Cname="数据库"));
//连接查询
select Sno,Sname
from S join SC on S.Sno=SC.Sno
join C on SC.Cno=C.Cno and C.Cname="数据库";
select Sno,Sname
from S,SC,C
where S.Sno=SC.Sno and SC.Cno=C.Cno and C.Cname="数据库";