实验目的:掌握单表select语句的使用,掌握聚合函数在查询中的应用方法。
2.实验原理:使用 SQL查询语句、SELECT语句、WHERE语句、运算符和比较条件、聚合函数、排序、分组、连接操作。
1.查询所有学生的成绩信息。
select * from student
2.查询学生的学号和姓名。
select sno,sname from student
3.查询所有学生的姓名和出生年。
select sname,year(getdate())-sage from student
4.查询所有学生的姓名和出生年,要求列名为汉字形式。
select sname as 姓名,year(getdate())-sage as 出生年 from student
5.查询CS系的所有学生信息。
select * from student where sdept='CS'
6.查询CS系的所有男同学信息。
select * from student where sdept='CS' and ssex='男'
7.查询年龄在18至20岁之间的学生信息。
select * from student where sage>=18 and sage<=20
8.查询年龄不在18至20之间的学生信息。
select * from student where sage<=18 or sage>=20
9.查询所在系为CS和JD的学生信息。
select * from student where sdept='CS'or sdept='JD'
10.查询姓张的学生的信息。
select * from student where sname like '张%'
11.查询姓名只有两个字且姓李的学生的学号和姓名。
select sno,sname from student where sname like '李_'
12.查询没有成绩的学生的学号和课程号。
select sno,cno,grade from sc where grade is null
13.查看CS系学生的年龄情况。
select distinct sage from student where sdept='CS' --distinct指消除重复行
14.查询前三个同学的信息。
select top 3 * from student
15.统计男学生人数。
select count(sno) as 男生人数 from student where ssex='男'
16.统计表sc中选修过课程的学生人数。
select count(distinct sno) as 学生人数 from sc
17.从表sc中查询所有成绩中最高分和最低分。
select max(grade) as 最高分,min(grade) as 最低分 from sc
18.统计学号为060314001的学生的总成绩和平均分。
select sum(grade) as 总成绩,avg(grade) as 平均成绩 from sc where sno='060314001'
实验小结:
函数名称 | 功能 |
AVG | 按列计算平均值 |
SUM | 按列计算值的总和 |
MAX | 求一列中的最大值 |
MIN | 求一列中的最小值 |
COUNT | 按列值统计个数 |
在查询的过程中,查询选修C1或C2的信息时,可以用“in”操作来查询属性值指定集合的元组。在查询所有姓张的同学时,用到了通配符“%”,它代表0个或多个字符,例如‘ab%’,‘ab’后可接任意字符串。还有通配符“_(下划线)”,代表一个字符,例如,‘a_b’,‘a’与‘b’之间可有一个字符。