oracle 分组查询详解,分组函数作用于一组数据,并对一组数据返回一个值
一,,什么是分组函数
分组函数作用于一组数据,并对一组数据返回一个值
二,分组函数类型
avg ,count,max,min,stddev(标准方差),sum。
函数名称
函数描述
count
返回找到的记录数
min
返回一个数字列或计算列的最小值
max
返回一个数字列或计算列的最大值
sum
返回一个数字列或计算列总和
avg
返回一个数字列或计算列的平均值
三,分组函数的语法
select [column,] group_function(column), ...
from table
[where condition]
[group by column]
[order by column];
//返回总记录数 //* 代表的是:一条记录
sql> select count(*) from emp;
//返回comm不为空的总记录数
sql> select count(comm) from emp;
//count(distinct expr) 返回 expr非空且不重复的记录总数
sql> select count(distinct(sal)) from emp;
注意:组函数忽略空值。
//返回所有员工的平均工资
sql> select avg(nvl(sal,0)) from emp;
注意:nvl函数使分组函数无法忽略空值
//返回员工编号最小值
sql> select min(empno) from emp;
//返回员工工资最大值
sql> select max(sal) from emp;
//求该月本公司发出的工资总额
sql> select sum(comm)+sum(sal) from emp;
sql> select sum(nvl(sal,0)+nvl(comm,0)) from emp;
group by
如果在查询的过程中需要按某一列的值进行分组,以统计该组内数据的信息时,就要使用group by子句。不管select是否使用了where子句都可以使用group by子句。
注意:group by子句一定要与分组函数结合使用,否则没有意义。
//求出每个部门的员工人数
sql> select deptno,count(*) as 人数 from emp group by deptno;
//求出每个部门的员工的平均工资
sql> select deptno,avg(nvl(sal,0)) from emp group by deptno;
//注意:group by 子句中的列不必包含在select 列表中
sql> select avg(nvl(sal,0)) from emp group by deptno;
//求出某个部门中相同职位的员工人数 group by 后可以跟多个分组的字段
sql> select deptno,job,count(*) from emp group by deptno,job order by deptno;
having 子句
having 子句对 group by 子句设置条件的方式与 where 子句和 select 语句交互的方式类似。where 子句搜索条件在进行分组操作之前应用;而 having 搜索条件在进行分组操作之后应用。having 语法与 where 语法类似,但 having 可以包含聚合函数。having 子句可以引用选择列表中出现的任意项。
备注:having子句通常与group by子句结合使用
语法:
select column, group_function
from table
[where condition]
[group by group_by_expression]
[having group_condition]
[order by column];
//查询部门的员工人数大于五部门编号
sql> select deptno,count(*) from emp group by deptno having count(*)>5;