2024年4月19日发(作者:)
实验三 单表查询
一、 实验目的
掌握简单
SQL
查询语句的应用,包括
like
、
top
、
order by
、
compute
和聚集函数的应用。
二、 实验内容
1
、基本查询
(
1
)查询
Student
表中全体学生的全部信息
select *
from Student
(
2
)查询全体学生的学号、姓名
select Sno, Sname
from Student
2
、查询时改编列标题的显示、
查询全体学生的学号、姓名、家庭地址信息,兵分别加上“学生“、“学
号”、“家庭地址”的别名信息
select Sno
学号
, Sname
姓名
, Home_addr
家庭住址信息
from Student
3
、条件查询
(
1
)、查询成绩大于
80
分的学生的学号及课程号、成绩
select Sno, Cno, Grade
from SC
where Grade>80
(
2
)查询成绩在
75~80
分的学生的学号及课程号、成绩
select Sno, Cno, Grade
from SC
where Grade between 75 and 80
3
)查询选秀了课程号为“
002
”且成绩大于
80
分的学生的学号
select Sno
from SC
where Cno=002 and Grade>80
(
4
)某些学生选秀某们课程后没有参加考试,所以有选课记录,但没有考
试成 绩,请查询缺少成绩单额学生的学号和相应的课程号
select Sno, Cno
from SC
where Grade=null
4
、基于
IN
子句的数据查询
从
Course
表中查询出”高数”、“
C
语言程序设计”的所有信息
select *
from Course
where Cname in( '
高数
' , 'C
语言程序设计
' )
5
、基于
between⋯
and
子句的数据查询 查询所有成绩在
70~80
分之间的学
生选课信息
select Sno, Cno, Grade from SC
where Grade between 70 and 80
6
、基于
like
子句的查询
(
1
)从
Student
表中分别检索出姓“张”的所有同学的资料
select *
from Student
where Sname like '
张
%'
(
2
)检索名字的第二个字是“红”或“虹”的所有同学的资料
select *
from Student
where Sname like '_
红
%' or Sname like '_
虹
%'
3
)查询课程名为
Visual_Basic
的课程的学分
select Credit
from Course
where Cname='Visual_Basic'
7
、使用
top
关键字查询
(
1
)从选课表中检索出前
3
个课程信息
select top 3 *
from SC
(
2
)从选课表中检索出前面
20%
的课程信息
select top 20 percent *
from SC
8
消除重复行
检索出学生逸轩课程的课程号,要求显示的课程号不重复
select distinct Cno
from SC
9
、查询经过计算的值
查询全体学生都的姓名及其年龄
select Sname, datediff (year , Brith , getdate ())
年龄
from Student
10
、使用
order by
语句对查询的结果进行排序
(
1
)显示所有学生的基本信息,按班级号排序,若班级号相同则再按学号排
序
select *
from Student
order by Classno asc
(
2
)查询全体学生的姓名及其年龄,并按学生的年龄的降序排列
select Sname, datediff (year , Brith , getdate ()) from Student
order by datediff (year , Brith , getdate ()) desc
11
、使用聚合函数 (
1
)查询学生的总人数
select COUN(T*)
from Student
(
2
)计算选秀了“
002
”号课程的学生的平均成绩、最高分、最低分
select
MAX( Grade ), MIN( Grade), AVG( Grade ) from SC where Cno='002'
12
、使用
group
子句进行查询 (
1
)查询各班级学生的总人数
select Classno , count
(Sno) from Student group by Classno
(
2
)汇总总分大于
150
分的学生的学号及总成绩
select Sno, SUM( Grade )
from SC group by Sno having SUM( Grade )> 150
(
3
)查询各个课程号相应的选课人数
select COUN(TSno)
from SC group by Cno
13
、使用
compute
和
compute by
子句进行查询 (
1
)汇总每个学生的学号及总
成绩
select Sno, Grade from SC order by Sno asc compute SUM( Grade) by Sno
(
2
)按学号汇总出每个学生的学号及总成绩、最高分、最低分以及所有学生
的 总成绩
select *
from SC order by Sno compute sum( Grade) compute sum( Grade), max( Grade ), min( Grade) by
Sno
问题、总结及体会
单表查询,相对简单,不过还是需要注意细节和前后关系
发布评论