oracle数据库(统计函数和分组查询)

来源:互联网 发布:医疗数据分析师 编辑:程序博客网 时间:2024/05/01 01:31
统计函数及分组查询
统计函数:
count():查询表中的数据总数
avg():求出平均值
sum():求和
max():求出最大值
min():求出最小值
分组查询:
分组的不成文规定:当数据重复时分组才会有意义,因为一个人也可以一组(没什么意义)
语法:
select [distinct]*|分组字段 [别名] [,分组字段2 [别名]],...] |统计函数
from 表名称 [别名], [表名称 [别名],...]
[where 条件(s)]
[group by 分组字段1[,分组字段2,...]]
[order by 排序字段 [asc|desc]] [,排序字段 [asc|desc],...]];
实例:
--按照部门编号分组,求出每个部门的人数,平均工资
-- group by 语句使用,除了统计函数以外,要查询的字段必须包含在group by 中
select deptno,count(*) total,trunc(avg(sal),2) avgsal from emp group by deptno
一旦分组后,会对语法上出现新的限制,对于分组有一下要求:
统计函数可以在没有分组的时候单独使用,可是却不能出现其他的查询字段;
统计函数单独使用:select count(*) from emp;
错误的使用,出现其他字段:select count(*),empon from emp
在分组的情况下,统计条件可以跟分组字段同时查询,但是其他字段不能查询
正确做法:select count(*),sal FROM emp group by sal;
错误做法:select count(*),sal,empon FROM emp group by sal;
having子句
如果要对分组后的数据再次进行过滤,则使用having子句完成
语法:
select [distinct]*|分组字段 [别名] [,分组字段2 [别名]],...] |统计函数
from 表名称 [别名], [表名称 [别名],...]
[where 条件(s)]
[group by 分组字段1[,分组字段2,...]]
[having 分组后的过滤条件(可以使用统计函数)]
[order by 排序字段 [asc|desc]] [,排序字段 [asc|desc],...]];
实例:统计平均工资大于2000的部门信息
-- 1.确定要查询的字段及表
select e.sal,d.deptno, d.dname, d.loc from emp e,dept d where e.deptno= d.deptno
-- 2.统计平均工资及部门信息
select avg(e.sal),d.deptno, d.dname, d.loc from emp e,dept d
where e.deptno= d.deptno group by d.deptno, d.dname, d.loc
-- 3.统计平均工资大于2000的部门信息
select trunc(avg(e.sal)) avg,count(*) total,d.deptno, d.dname, d.loc from emp e,dept d
where e.deptno= d.deptno group by d.deptno, d.dname, d.loc
HAVING avg(e.sal)>2000
注意点:where和having的区别
where:是在执行group by操作之前进行过滤,表示从全部数据中筛选出部分的数据,在where之中不能使用统计函数;
having:是在group by分组之后的再次过滤,可以在having子句中使用统计函数
select语句顺序:
写的顺序:select...from...where...group by... having... order by...
执行顺序:from...where...group by...having...select...order by...

原创粉丝点击