sql server 查询

来源:互联网 发布:打色子软件 编辑:程序博客网 时间:2024/06/07 17:39
use Jacob 
go






--1.查询所有的记录
select * from 学生表


--2.查询指定字段
select ID 姓名 from 学生表


--3.在查询结果中使用表达式,
 --以及改变显示的列标题
select ID*10,姓名 from 学生表
select '学号' = ID*10,姓名+'酱' as '昵称'  from 学生表


--4.显示部分查询结果
select top(2) id,姓名 from 学生表
select top(25)percent id,姓名 from 学生表 --按百分比查询(只入不舍)


--5.带限定条件的查询
select * from 学生表
where not 姓名 = '张三'


--6.带and的多条件查询
select * from 学生表 
where 性别 = '男'and 生日>= '1991-9-10' 




--7.带or的多条件查询
select * from 学生表
where 性别 = '女' or 生日 <= '1990-2-12'




--8.使用like运算符进行模糊查询
select * from 学生表
where 姓名 like '[李]%'  --使用通配符  % _  []  [^]


select * from 学生表
where 姓名 like '%[山]%'   --名字里面带山的查询




select * from 学生表
where 姓名 like '_[山]_'


select * from 学生表
where 姓名 like '[山]_'






--9.使用between and进行查询
select * from 学生表
where 生日 between '1990-1-20' and '1991-2-10'   --查询1990年到1991年之间数据




--10.对查询结果排序
select * from 学生表
order by 班级ID desc , ID    --降序排列






--11.使用GROUP BY分组(常跟聚合函数一起使用)
select * from 


select * count(*),班级类型
form 班级表
group by 班级类型    --查询班级开了多少次 




--在查询结果中插入字符串常量
select '学号', id from 学生表




--嵌套查询  使用in
--查询出所有学习 数据库的学生
select * from 学生表
where 班级ID in 
(
select ID from  班级表
where 班级类型 = '数据库'
)




--嵌套查询,使用exists
--查询是否存在,数据库班,存在,则查出所有女学员


select * from 学生表
where 性别 = '女' and exists
(
select id from 班级表
where 班级类型= '数据库班'

)


/*********************************************************/


多表查询


/*********************************************************/


--内连接
--查询所有11期的学生信息
select * from 学生表,班级表
where 学生表.班级ID =  班级表.ID and 班级名 = '11期'




--外链接
--左外
select * from 学生表 left outer join 班级表
on 学生表.班级ID =  班级表.ID and 班级名 = '11期'




--右外连接


select * from 学生表 right outer join 班级表
on 学生表.班级ID =  班级表.ID and 班级名 = '11期'



























0 0
原创粉丝点击