1.select 语句基本结构(注意顺序)
select 数据列表 [into]新表 [from 表(或视图、子查询)] [where 查询条件] [group by 分组表达式] [having 查询条件] [order by 排序条件[asc | desc]]
2. select 语句
获取简单的数据
select stuno 学号,stuname 姓名,sex 性别 from t_student select * from t_student 如果命名有空格的,需要把整个命名用方括号"[ ]"(有时可以用单引号)括起来 select stuno [学 号],stuname '姓 名',sex '性;别 ' from t_student
显示常量、函数、表达式(以九九乘法表为例)
--定义三个局部变量 declare @i int,@j int,@temp varchar(200) --初始化值 set @i = 1 set @temp = '' while @i <= 9 --使用while循环 begin set @j = 1 --初始化j while @j <= @i--循环遍历列数 begin --cast一种数据类型转换为另一种数据类型 char(9)制表符 set @temp += cast(@j as varchar(10)) + '*' + cast(@i as varchar(10)) + '=' + cast(@i*@j as varchar(10)) + char(9) set @j +=1; end print @temp --输出 set @temp = '' set @i += 1 end
3.where 条件 语句
查询条件为年龄大于等于30的
select * from t_test where t_test.age>=30
查询条件为年龄不是大于等于30的
select * from t_test where not(t_test.age>=30)
查询条件为年龄不是不大于20的
select * from t_test where not(t_test.age!>20)
查询成绩在70-90分之间的数据
select * from t_test where score between 70 and 90
查询成绩不在70-90分之间的数据
select * from t_test where score not between 70 and 90
查询无成绩的学生
select stuname from t_test where score is null
精准查询
select stuno,stuname,sex,age from t_test where stuname in('刘备','孙尚香')
模糊查询(%表示所有,_表示单个字符)
select * from t_test or (stuname like '刘_') and (stuname like '刘__')
4.order by 排序 asc 升序(默认)desc 降序
查询成绩在70-90的并且根据成绩排序(升序)
select * from t_test where score between 70 and 90 order by score
姓名升序,成绩倒序
select * from t_test where score between 70 and 90 order by stuname asc,score desc
猜猜这个和上面语句的结果一样吗?
select * from t_test where score between 70 and 90 order by score desc,stuname asc
5.group by 字句 需要和count(*)函数一起使用
计算性别人数(count(*)集合函数,可写成count(1)或count(sex))
select sex as 性别, count(1) as 人数 from t_test group by sex order by 性别 desc
查询男女平均成绩
select sex 性别,avg(score) 平均成绩 from t_test group by sex
6.having 字句
指定组或聚合的检索条件,功能与where类似 ,having 与 where 的区别:where 过滤行,having过滤分组
过滤性别大于4的人数
select sex 性别,count(*) 人数 from t_test group by sex having count(*) > 4 --having 要与count(*)联系
7.使用top表达式(可以返回某一数量的行或者某一百分比的行)
显示表中前四行
select top 4 * from t_test
显示男女各前30%的行
select top 30 percent * from t_test where sex = '男' select top 30 percent * from t_test where sex = '女'
显示最后两行(并且为升序)
select top 3 * from (select top 2 * from t_test order by stuno desc)a order by stuno
显示任意行数(2为需要显示的行数,5为选定的区域)
select top 2 * from (select top 5 * from t_test order by stuno desc)b order by stuno
8.select into 子句 (可以动态创建新表)
创建表t_tmp,把t_test表的数据复制到新表中
select * into t_tmp from t_test
选取表中部分数据创建新表
select stuname 姓名,birthday 年龄 into t_tmp from t_test select * from t_tmp