第九章 数据查询基础
查询基础
显示全部列
- 格式:select *from 表名
- 演练:
代码:select * from students;
第二种方法:
将表拖到命令代码区
显示指定列
- 格式:select 列1,列n from 表名;
- 演练:查询表中只显示指定列的数据
限定条件
- 格式:select * from 表名 where 条件
- 演练:查询表中符合条件的数据
表头起别名
- 格式:1,select 列1 as 表头1,列n as 表头n from 表名;
2,列名 表头;
3,select 表头1=列1,表头n=列名n from 表名; - 演练:查询表中数据 指定显示的列名并且以中文显示的表头
查询空值
-
格式:列名 is null(查询字段值是null的)
列名 is not null(查询字段值为非null的) -
演练:查询出某个列为空的所有数据
使用常量列
- 格式:select 表头1=列名1,常量表头名=常量值 from Students;
- 演练:查询数据给每条数据添加一个常量列。
获得一定百分比的数据
- 格式:select top 百分多少 percent * from 表名;
查询
排序
- 格式:
–(升序)1,order by 列名称;2,order by 列名 asc
–(降序)order by 列名称 desc;
–(多列排序)order by 列名1模式,列名2模式;
函数
字符串函数
-
charindex 功能:
查询一个字符串在另一个字符串的起始位置 -
格式:charindex(子字符串,总字符串)
-
len 功能:返回字符串的长度
-
格式:len(字符串);
-
upper 功能:字符串转为大写
-
格式:upper(字符串);
-
ltrim 功能:清除字符串左边的空格
-
格式:ltrim(字符串);
-
rtrim 功能:清除字符串右边的空格
-
格式:rtrim(字符串);
-
right 功能:从字符串右边返回指定数量的字符
-
格式:right(字符串,长度);
-
left 功能:从字符串左边返回指定数量的字符
-
格式:left(字符串,长度);
-
replace 功能:替换
-
格式:replace(原字符串,把什么内容,替换为什么)
-
stuff 功能:删除指定长度的字符串,并在该位置插入一个新的字符串
-
格式:stuff(原字符串,起点值,删除几个,插入几个字符串)
日期函数
-
日期单位名称
-
year,yy,yyyy
-
month,mm,m
-
day,dd,d
-
weekday,dw,w
-
hour,hh
-
minute,mi,n
-
second,ss,s
-
getdate 功能:获取当前的系统日期
-
格式:getdate();
-
dateadd 功能:日期加法,指定一个数字,指定一个单位,返回相加后的日期
-
格式:dateadd(时间单位,增量值,时间字符串)
-
演练:月相加
日相加:
等等以此类推。 -
datediff 功能:两个日期之间定日期部分的间隔
-
格式:datediff(时间单位,时间字符串1,时间字符串2)
-
演练:时间差,月份之差
时间差,年份
以此类推。
小结:第二个时间减第一个时间的差 -
datename 功能:返回一个时间的指定单位的值
-
格式:datename(单位,日期字符串)
-
演练:日
周:
以此类推。 -
datepart 功能:返回日期对象的指定单位的值
-
格式:datepart(日期单位,日期字符串)
-
演练:月
以此类推。
查询一定量的数据
- 按百分比查询:
- 格式:select top 条目数* from 表名;
- 列子:select top 2 * from partment;
- 按条目数查询
- 格式:select top 百分比 percent *from 表名;
查询条件
- 查询为空时 格式:where 列名 is null;
- 查询非空时 格式:where 列名 is not null;
模糊查询
通配符
-
_代表一个
-
例子:select * from table_2 where name like‘__’;
- %
- 例子:select * from Table_2 where name like ‘%白%’;
- 字符集:[内容a,内容b]
- 例子:select * from 表名 where 列名 like ‘[孙,李]%’;
- 字符集取反 :[^内容c,内容d]
范围查找
- betw…and
- 格式:列名 between 最小值 and 最大值
- 例子:select * from goods where name like ‘%小米%’ and name like ‘%手机%’ and price between 1399 and 2000;
- …and…
- 格式:列名>=最小值 and 列名<=最大值
- 例子:select * from goods where name like ‘%小米%’ and name like ‘%手机%’ and price >=1000 and price <= 2000;