简单sql查询语句应用
1. 基本查询
select *
from Student
go
select sno,sname
from Student
go
2. 查询时改变列标题的显示
- 查询全体学生的学号、姓名、家庭地址信息,并分别加上“学生”、“学号”、“家庭地址”的列名信息。
select sno as 学号,sname 姓名,家庭地址=Home_addr
from Student
go
(加不加引号貌似都行)
3. 条件查询
select Sno,Cno,Grade
from SC
where Grade>80
go
select Sno,Cno,Grade
from SC
where Grade between 75 and 80
go
- 查询选修了课程号为“002”且成绩大于80分的学生的学号
select Sno
from SC
where Cno=002 and Grade>80
go
- 某些学生选修某门课程后没有参加考试,所以有选课记录,但没有考试成绩,请查询缺少成绩的学生的学号和相应的课程号
select Sno,Cno
from SC
where Grade=0
go
4. 基于in子句的数据查询
- 从Course表中查询出“高数”、“C语言程序设计”的所以信息
select *
from Course
where cname in ('高数','C语言程序设计')
go
(这里就一定要加引号了)
5.基于between···and子句的数据查询
select *
from SC
where Grade between 70 and 80
go
6.基于like子句的查询
%(百分号)代表任意长度(可为0)的字符串
-(下横线)代表任意单个字符
- 从Student表中分别检索出姓“张”的所以同学的资料
select *
from Student
where sname like '张%'
go
- 检索名字的第二个字是“红”或“虹”的所以同学的资料
select *
from Student
where sname like '_红%' or sname like '_虹%'
go
- 查询课程名为Visual_Basic的课程的学分(提示用escape短语)
select Credit
from Course
where Cname like 'Visual\_Basic' escape'\'
go
7.使用top关键字查询
select top 3 *
from Course
go
select top 20 percent *
from Course
go
8.消除重复行
- 检索出学生已选课程的课程号,要求显示的课程号不重复
select distinct Cno
from SC
go
(distinct 短语去重 针对一条记录而不是一列)
9.查询经过计算的值
- 查询全体学生的姓名及其年龄(提示:利用系统函数getdate())
select sname,age=datediff(yy,Birth,getdate())
from Student
go
(getdate()函数获取当前时间,datediff(datepart,startdate,enddate)三个参数返回两个日期间的时间)
10.使用order by 语句对查询的结果进行排序
- 显示所有学生的基本信息,按班号排列,若班号相同则再按学号排列
select *
from Student
order by Classno,Sno
go
- 查询全体学生的姓名及其年龄,并按学生的年龄的降序排列
select sname,age=datediff(yy,Birth,getdate())
from Student
order by age desc
go
(asc 升序 从小到大;desc 降序 从大到小)
11.使用聚合函数
select count(sno)
from Student
go
- 计算选修了“002”号课程的学生的平均成绩,最高分,最低分
select avg(Grade) 平均分,max(Grade)最高分,min(Grade) 最低分
from SC
where Cno=002
go
12.使用group 子句进行查询
select count(sno)人数
from Student
group by Classno
go
select Sno,sum(Grade)
from SC
group by Sno
having sum(Grade)>150
go
group by 分组依据列
having 组提取条件 (分组后筛选)
select count(Sno) 选课人数
from SC
group by Cno
go
13.使用compute 和compute by子句进行查询
提示compute附近有语法错误,可能是版本不支持吧~未知