SQL学习笔记四 聚合函数、排序方法
zycchun 2019-04-04
聚合函数 count,max,min,avg,sum...
select count (*) from T_Employee
select Max(FSalary) from T_Employee
排序 ASC升序 DESC降序
select * from T_Employee order by Fage
先按年龄降序排列。如果年龄相同,则按薪水升序排列
select * from T_Employee order by FAge DESC,FSalary ASC
order by 要放在 where 子句之后
通配符过滤
通配符过滤用like
单字符通配符‘_'
多字符通配符‘%'
select * from T_Employee where FName like '_erry'
NULL 是不知道的意思,而不是没有
用SQL语句查询NULL的数据不能用=或<> 而用is NULL或者is not NULL
select * from T_Employee where FName is NULL
in(23,25)同时匹配两个值。相当于 23 or 25
between 20 and 30 匹配介于20到30之间的数
group by分组
select FAge, count(*) from T_Employee
Group by Fage
先把相同的Fage分一组,再统计每一组的个数
group by子句要放在where子句之后。如果想取某个年龄段人数大于1的,不能用where count(*) > 1 ,因为聚合函数不能放在where子句之后。要用having子句
Having是对分组后的列进行过滤,能用的列和select中的一样。如下例中则不能用having Fsalary>2000 只能用where Fsalary>2000
select FAge, count(*) from T_Employee
Group by FAge
having count(*) > 1;
限制结果集的范围
select Top 3 * from T_Employee
order by FSalary DESC
从第六名开始选3个.2005后可以用Row_Number函数
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