安徽工程大学数据库实验五-sql数据查询
--(1)查询姓名中第二个字为“勇”的男学生的姓名和班级。
select sname,clno
from student
where sname like '_勇%' and ssex = '男';
--(2)查询成绩为 68、78、88 和 98 的选修记录。
select *
from cj
where grade in (68,78,88,98);
--(3)查询选修了“4”号课程没有成绩的学生学号。
select sno
from cj
where cno = 4 and grade is null;
--(4)查询“00311”班所有女生的学号、姓名和出生年份。
select sno,sname,2022-sage
from student
where ssex='女' and clno=00311;
--(5)查询“李勇敏”同学的班长姓名。
select sname,sno
from student
where sno = (select monitor
from class
where clno=(select clno
from student
where sname = '李勇敏'));
--(6)查询“2001102”同学的选课门数。
select count(*)
from cj
where sno = '2001102';
--(7)统计学生表中的班级数
select count(distinct clno)
from student;
--(8)查询“00311”班每位同学的课程平均分
select sno,AVG(grade)
from cj
group by sno
having sno in (select sno
from student
where clno = 00311);
--(9)查询哪些学生最低分大于 70,最高分小于 90,
-- 输出他们的学号。
select sno
from cj
group by sno
having min(grade)>70 and max(grade)<90;
--(10)计算 Student×Cj×Course 的结果
select *
from student,cj,course
where student.sno = cj.sno;
--(11)以 clno 升序、Sage 降序列出 Student 表的学生信息。
select *
from student
order by sage desc,clno asc;
--(12)列出成绩高于学号为“2000101”、课程号为“3”
-- 的成绩的所有选课记录。
select *
from cj
where grade > (
select grade
from cj
where sno = '2000101' and cno = 3
)
--(13)查询和“张婷婷”同学在同一班级的学生信息。
select *
from student
where clno in (
select clno
from student
where sname='张婷婷'
)
--(14)查询不及格课程在三门及以上的同学
--没有符合题意的数据,所以我又编造了一些数据插入表格中
update Cj
set Grade=55
where Sno='2000101' and Cno=1;
update Cj
set Grade=50
where Sno='2000101' and Cno=3;
update Cj
set Grade=45
where Sno='2000101' and Cno=5;
select Sno ,count(Cno)
from Cj
where Grade < 60
group by (Sno)
having count(Cno) >= 3;
--(15)查询选修了目前 Course 中所有课程的同学。
select *
from Student
where not exists
(select * from Course where not exists
(select *
from Course
where Sno=Student.Sno
and Cno=Course.Cno));
/*Exists执行的流程Exists首先执行外层查询,再执行内存查询,与IN相反。
流程为首先取出外层中的第一元组,再执行内层查询,
将外层表的第一元组代入,若内层查询为真,即有结果时。
返回外层表中的第一元 组,接着取出第二元组,执行相同的算法。
一直到扫描完外层整表 。*/
-- 建立一个表
create table avgGrade
( Sno char(7) not null primary key,
avggrade int not null
);
--(16)对每位同学,求平均成绩,并把结果存入新建立的表中。
insert
into avgGrade(Sno,avggrade)
select Sno,avg(grade)
from cj
where Sno in (
select Sno
from Student
)
group by Sno;
--(17)将班级号为“00311”班级的所有女学生的成绩加 5 分(原题是01312)
update cj
set grade +=5
where Sno in (
select Sno
from student
where Clno='00311' and Ssex='女'
);
--(18)删除“01311”班级的所有学生的成绩记录。
delete
from cj
where Sno in(
select Sno
from student
where clno = '00311'
);