享成:本人大学生一枚,只为分享知识,别无他求。
争当做个有理想,有抱负的人!
热情诠释青春,微笑传递正能量。
个人公众号:飞享
SQL语句练习题
一、 创建以下四个表
1)department 表(院系编号、院系名称),deptNo是主键。
create table department
(
deptNo smallint PRIMARY KEY not null,
deptName varchar(50)
);
2)student表(学号、姓名、年龄、性别、院系),sno是主键,deptNo是外键。
create table student (
deptsno char(8) PRIMARY KEY not null,
deptsname varchar(8),
deptsage smallint,
ssex char(2),
deptNo smallint,
FOREIGN KEY(Cno)REFERENCES department(deptNo)
);
3)course表(课程号、课程名、先修课、学分、院系编号),cno是主键。
Create table course (
cno char(4)PRIMARY KEY not null,
cname varchar(50,
pno char(4),
credit int,
deptNo smallint);
4)选课表(学号、课程号、成绩),学号和课程号联合做主键。
create table s
(
sno char(8) primary key,
cno char(4) primary key,
grade int not null
);
二、 创建索引
- 创建Student的姓名字段的索引
create unique index StuSname on Student(Sname); - 创建SC表的课程号升序、成绩降序索引
create unique index CouCno ON SC(Cno);
create unique index Scno ON SC(Cno DESC);
三、 SQL查询
单表 - 检索计算机系的学生。
select *
from d
where dname=‘计算机’;
2. 检索年龄大于20岁的女学生的学号和姓名。
select sno,sname
from s
where age>20;
- 检索姓名以王打头的所有学生的姓名和年龄。
select sname,age
from s
where sname like’王%’
- 查询姓名为‘X国X’同学。
select sname,age
from s
where sname like’国’;
- 在SC中检索成绩为空值的学生学号和课程号。
select sno,cno
from sc
where grade is null;
- 输出c01课程的成绩单,要求成绩按从高到低排序。
select sno,grade
from sc
where cno=‘c01’
order by grade desc;
7. 求选修C04课程的学生的平均分。
select 'c04’cno,AVG(grade)avg
from sc
where cno=‘c04’
8. 每个学生选修的课程门数。
select sno,COUNT(cno)sumcno
from sc
group by sno;
- 检索至少选修两门课程的学生学号。
select sno,COUNT(cno)sumcno
from sc
group by sno
having COUNT(cno)>2;
- 求每个学生平均成绩。
select sno,AVG(grade)avg
from sc
group by sno;
- 统计每门课程的学生选修人数(超过3人的课程才统计)。查询结果按人数降序排列,若人数相同,按课程号升序排列。
select cno,COUNT(sno)sumcno
from sc
group by cno
having COUNT(sno)>3
order by COUNT(sno) desc,cno asc;
多表联合查询
12. 检索每个学生的总学分,输出学号、姓名、院系和总学分,按院系排序。
select x.sno,x.sname,sum(x.credit)sumcredit,x.dname
from
(
select s.sno,sname,s.dept,sc.cno,c.credit,d.dname
from s,sc,c,d
where s.s