聚集函数
■avg()
SELECTAVG(sal) FROM EMP;
SELECT AVG(sal +200) FROM EMP;
SELECTCOUNT(*) FROM EMP;
SELECTCOUNT(empno)FROM EMP;
SELECTCOUNT(rowid)FROM EMP;
SELECT MAX(sal),MIN(sal) FROM EMP;
SELECT MAX(ename),MIN(ename) FROM EMP;
SELECT MAX(hiredate),MIN(hiredate) FROM EMP;
SELECTSUM(sal)FROM EMP;
■分组
SELECTdeptno FROMEMP GROUP BY deptno;
SELECTdeptno,job FROMEMP GROUP BY deptno,job;
Selectdeptno,avg(sal),count(empno)from EMP
Groupby deptno;
Selectjob ,max(sal),min(sal)from EMP group by job
order by job;
可以多分组统计的结果,使用聚集函数进行排序
select deptno,avg(sal) from EMP;
SELECT...FROM …WHERE
GROUPBY ...
HAVING ...
ORDERBY ...;
SELECTdeptno, AVG(sal) FROM EMP
GROUPBY deptno HAVING AVG(sal) > 900;
例:
/*如何显示所有员工中最高工资和最低工资*/
select * from emp;
select max(e.sal) as"最高工资", min(e.sal) as"最低工资",avg(e.sal),sum(e.sal),count(*) from emp e;
/*请显示工资最高的员工的名字,工作岗位*/
select em.ename, em.job, em.sal
from emp em
where em.sal = (select max(e.sal) from emp e);
select em.ename, em.job, max(em.sal)
from emp em
group by em.ename, em.job
having max(em.sal) = (select max(e.sal) from emp e);
/*请显示工资高于平均工资的员工信息*/
select e.* from emp e where e.sal>(select avg(em.sal) from emp em);
/*请显示工资高于所在部门平均工资的员工信息*/
select em.empno,
em.ename,
em.job,
em.mgr,
em.hiredate,
em.sal,
em.deptno,
emp1.avgsal
from emp em,
(select avg(e.sal) as avgsal, e.deptno as deptno
from emp e
group by e.deptno) emp1
where em.deptno = emp1.deptno
and em.sal > emp1.avgsal