数据删除
(1)
删除表中的全部数据:
delete from T_Person
。
(2) delete
只是删除数据,表还在,和
drop table
不同。
(3) delete
也可以带
where
子句来删除一部分数据:
delete from T_Person where FAge>30
。
数据检索
(1)
简单的数据检索:
select * from T_Employee
。
(2)
只检索需要的列:
select FName from T_Employee
。
(3)
列别名:
select FNumber as
编号
,FName as
姓名
from T_Employee
。
(4)
还可以检索不与任何表关联的数据:
select 1+1
,
select newId()
,
select getDate()
。
数据汇总
(1) SQL
聚合函数:
max(
最大值
)
,
min(
最小值
)
,
avg(
平均值
)
,
sum(
和
)
,
count(
数量
)
。
数据排序
(1) order by
子句位于
select
语句的末尾,它允许指定按照一个列或者多个列进行排序,还可以指定排序方式是升序
(
从小到大排序,
ASC)
还是降序
(
从大到小排序,
DESC)
。
(2)
按照年龄从大到小排序,如果年龄相同则按照工资从大到小排序
select * from T_Employee order by FAge Desc,FSalary Desc
(3) order by
子句要放到
where
子句之后:
select * from T_Employee where FAge>23 order by FAge Desc,FSalary Desc
通配符过滤
(
模糊匹配
)
(1)
通配符过滤使用
Like
。
(2)
单字符匹配的通配符为半角下划线
”_”
,它匹配单个出现的字符,以任意字符开头,剩余部分为
”erry”
:
select * from T_Employee where FName like ‘_erry’
(3)
多字符匹配的通配符为半角百分号
”%”
,它匹配任意次数
(
零或者多个
)
出现的任意字符,
”K%”
匹配以
K
开头,任意长度的字符串。检索姓名中包含
”n”
的员工的信息:
select * from T_Employee where FName like ‘%n%’
空值处理
(1)
数据库中,一个列如果没有指定值,那么值就为
null
,这个
null
和
C#
中的
null
不一样,数据库中的
null
表示
”
不知道
”
,而不是表示没有,因此
select null+1
结果是
null
,因为
”
不知道
”
加
1
的结果还是
”
不知道
”
。
(2) select * from T_Employee where FName=null and select * from T_Employee where FName!=null
。都没有任何返回结果,因为数据库
”
不知道
”
。
(3) SQL
中使用
is null
,
is not null
来进行空值判断。
select * from T_Employee where FName is null
select * from T_Employee where FName is not null
多值匹配
(1) select FAge,FNumber,FName from T_Employee where FAge in(34,23,35)
(2)
范围值:
1) select * from T_Emploee where FAge>=23 and FAge<=27
2) select * from T_Employee where Fage Between 23 and 27
数组分组
(1)
按照年龄进行分组统计各个年龄段的人数:
select FAge,Count(*) from T_Employee Group by Fage
(2) Group by
子句必须放在
where
语句的后面
(3)
没有出现在
Group by
子句中的列是不能放到
select
语句后的列名列表中的(聚合函数除外)。
1)
错误:
select FAge,FSalary from T_Employee group by Fage
。
2)
正确:
select Fage,Avg(FSalary) from T_Employee group by Fage
。
Having
子句
(1)
在
where
中不能使用聚合函数,必须使用
Having
,
Having
要位于
Group by
之后。
select Fage,Count(*) as
人数
from T_Employee Group by FAge Having Count(*)>1
(2)
注意
Having
中不能不能使用为参数分组的列,
Having
不能代替
where,
作用不一样,
Having
是对组进行过滤。
限制结果集行数
(1) select top 5 * from T_Employee order by FSalary Desc
(2) (*)
检索按照工资从高到低排序检索从第六名开始一共三个人的信息
select top 3 * from T_Employee where FNumber not in (select top 5 FNumber from T_Employee order by Fsalary desc) order by FSalary Desc
。
(3) SQL Server2005
后增加了
Row_Number
函数简化实现
去掉数据重复
(1) select FDepartment from T_Employee——>select distinct FDepartment from T_Employee
(2) distinct
是对整个结果集进行数据重复处理的,而不是针对某一个列,因此下面的语句并不会只保留
Fdepartment
进行重复值处理。
select distinct FDepartment,FSubcompany from T_Employee