SQL学习笔记四 聚合函数、排序方法
程序员文章站
2023-12-15 21:38:22
聚合函数 count,max,min,avg,sum... select count (*) from t_employee select max(fsalary) fro...
聚合函数 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
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