执行顺序
from
where
group by
having
select
order by
多表查询与分组查询的时候,查询结果相当于是一张临时表,所有的分组是在临时表操作
分组统计查询
COUNT()
MAX()
MIN()
SUM()
AVG()
MAX,MIN(数字,日期)
SELECT MAX(SAl),MIN(sal) FROM emp;
SELECT MAX(HIREDATE),MIN(HIREDATE) FROM emp;
SELECT SUM(SAl),AVG(sal) FROM emp;
SELECT TRUNC(AVG(MONTHS_BETWEEN(SYSDATE,hiredate)/12)) FROM emp; COUNT
统计条数
SELECT COUNT(*) FROM emp;
统计不为null的数量
SELECT COUNT(comm) FROM emp;
去重后的数量
SELECT COUNT(DISTINCT job) FROM emp; 分组统计查询
GROUP BY SELECT job,count(empno),AVG(sal)
FROM emp
GROUP BY job; SELECT job,count(empno),AVG(sal)
FROM emp
GROUP BY deptno; 限制1,有统计函数,没有group by 时,不允许有单独字段
例如:select Count(*) ,ename from emp;
限制2:在group by 语句中,select 语句后只允许出现统计函数和group by后的字段
限制3:统计函数嵌套查询,在嵌套查询时,只允许出现统计函数
错误
SELECT deptno,Max(AVG(sal))
FROM emp
GROUP by deptno
正确
SELECT Max(AVG(sal))
FROM emp
GROUP by deptno 理解分组:先求满足数据的数据,在分组
第一步 查询
SELECT d.deptno,d.dname,d.loc,e.empno,e.hiredate
from emp e,dept d
where e.deptno(+) = d.deptno;
第一步 分组
SELECT d.deptno,d.dname,d.loc,count(e.empno),AVG(MONTHS_BETWEEN(SYSDATE,e.hiredate)/12)
from emp e,dept d
where e.deptno(+) = d.deptno
group by d.deptno,d.dname,d.loc SELECT job,avg(sal)
FROM emp e
group by job
having avg(sal)>2000
where 不允许使用统计函数,发生在group by 之前
having 可以使用统计函数,group by 之后