目录
[1. 查询学生的姓名、性别、班级名称,并把结果存储在一张新表中。](#1. 查询学生的姓名、性别、班级名称,并把结果存储在一张新表中。)
[2. 查询男生的资料。](#2. 查询男生的资料。)
[3. 查询所有计算机系的班级信息。](#3. 查询所有计算机系的班级信息。)
[5. 查询年龄小于30岁的女同学的学号和姓名。](#5. 查询年龄小于30岁的女同学的学号和姓名。)
[6. 查询所有被选修的课程号。](#6. 查询所有被选修的课程号。)
7.在学生基本信息表Student中检索学生的姓名和出生年份,输出的列名为STUDENT_NAME和BIRTH_YEAR。
8.在StudnetGrade中,求选修课程"0511"且分数排名为前10%学生的学号和得分。
10.查询课程"0101"的成绩在80与90之间的同学的学号。
用SQL语句完成下列查询。使用数据库为SCHOOL数据库
1. 查询学生的姓名、性别、班级名称,并把结果存储在一张新表中。
Sql语句:
sql
select Stu_name,Stu_sex,Class_name
into Stu_Cla
from Student s left outer join Class c
on s.Class_id = c.Class_id;
运行结果:
![](https://img-blog.csdnimg.cn/direct/f0a00b0942af47c5a80bf80a3d69b03a.png)
2. 查询男生的资料。
Sql语句:
sql
select * from Student where Stu_sex = '男';
运行结果:
![](https://img-blog.csdnimg.cn/direct/a879c15996b746a5ab25015d2305f9f2.png)
3. 查询所有计算机系的班级信息。
Sql语句:
sql
/*连接查询*/
select c.*
from Class c,
Deparment d
where d.Depar_name = '计算机系'
and d.Depar_id = c.Depar_id;
/*子查询*/
select *
from Class
where Depar_id = (select Depar_id from Deparment where Depar_name = '计算机系');
运行结果:
![](https://img-blog.csdnimg.cn/direct/1d4e85a765e44d109b0b91953a24341a.png)
4.查询艾老师所教的课程号。
Sql语句:
sql
/*可能有多位艾老师,模糊查询;也可能教多门课程,distinct去重*/
select distinct Course_id
from Teacher t,
CourseTeacher ct
where t.Teac_name like '艾%'
and t.Teac_id = ct.Teac_id;
运行结果:
![](https://img-blog.csdnimg.cn/direct/e7478b6ca9064e779fa9d2fa023bb08b.png)
5. 查询年龄小于30岁的女同学的学号和姓名。
(获取系统当前时间函数:getdate(),获取时间的年份函数:year,获取月份函数:month,获取"日"函数:day)
Sql语句:
sql
select Stu_id, Stu_name
from Student
where year(getdate()) - year(Birthday) < 30
and Stu_sex = '女';
运行结果:
![](https://img-blog.csdnimg.cn/direct/15136365709642cf819bf36a4d731c0d.png)
6. 查询所有被选修的课程号。
Sql语句:
sql
/*有学生成绩的就是被选修了的,注意去重*/
select distinct Course_id from StudentGrade;
运行结果:
![](https://img-blog.csdnimg.cn/direct/86cc3d24160048baac1fedef82da9ba8.png)
7.在学生基本信息表Student中检索学生的姓名和出生年份,输出的列名为STUDENT_NAME和BIRTH_YEAR。
Sql语句:
sql
select Stu_name STUDENT_NAME, year(Birthday) BIRTH_YEAR
from Student;
运行结果:
![](https://img-blog.csdnimg.cn/direct/5d380992dd88498bb7df6152081bfcf9.png)
8.在StudnetGrade中,求选修课程"0511"且分数排名为前10%学生的学号和得分。
(Top 10 percent)
Sql语句:
sql
select top 10 percent Stu_id, Grade
from StudentGrade
where Course_id = '0511'
order by Grade desc;
运行结果:
![](https://img-blog.csdnimg.cn/direct/6c4e5101d2654ea88488455270ea1721.png)
9.查询选修课程号为"0109"或"0111"的学生学号。
Sql语句:
sql
select distinct Stu_id
from StudentGrade
where Course_id in ('0109', '0111');
运行结果:
![](https://img-blog.csdnimg.cn/direct/f0bdbf23c3d94e27b5b47b268bacfcd8.png)
10.查询课程"0101"的成绩在80与90之间的同学的学号。
Sql语句:
sql
select Stu_id
from StudentGrade
where Course_id = '0101'
and Grade between 80 and 90;
运行结果:
![](https://img-blog.csdnimg.cn/direct/6c1a9196f7544b4884dd3aae69ee2990.png)
11.查询平均成绩都在80分以上的学生学号及平均成绩。
(group by)
Sql语句:
sql
select Stu_id, avg(Grade) avgGrade
from StudentGrade
group by Stu_id
having avg(Grade) > 80;
运行结果:
![](https://img-blog.csdnimg.cn/direct/59081b54de6247eb97afad8cb62a4902.png)