Oracle命令(五)--多行函数


--求员工表的最高工资,最低工资,平均工资,所有工资

 

select max(sal) 最高工资, min(sal) 最低工资, avg(sal) 平均工资, sum(sal) 所有工资 from emp;


--求平均奖金

 

select avg(comm) 方式1, sum(comm)/count(empno) 方式2, sum(comm)/count(comm) 方式3 from emp;

 

因为 奖金一栏中含有空值,组函数会滤空,所以方式2的结果会区别1,3。

==>如果想要滤空修正

 

select count(empno) AA , count(nvl(comm, 0)) BB from emp;

 


分组数据(GROUP BY)

GROUP BY 子语句语法

select ...
from tab
where colum > 10
order by ...
GROUP by ...

 

--求出 EMPLOYEES 表中各个部门的平均工资

 

select deptno, avg(sal)
from emp
group by deptno

 

--求不同部门的不同工种的平均工资

 

select deptno, job, avg(sal)
from emp
group by deptno, job
order by 1

 

[注:]select 后面跟的选项需要在 group by 后面的选项中有体现

 

--查询平均工资大于 2000 的部门

 

select deptno, avg(sal)
from emp
group by deptno
having avg(sal) > 2000

 

--求十号部门的平均工资

先分组再过滤

 

select deptno, avg(sal)
from emp
group by deptno
having deptno = 10

 

先过滤,再分组(首选)

 

select deptno, avg(sal)
from emp
having deptno = 10
group by deptno

 

多表查询

等值连接

示例:
查询员工信息,员工号,姓名,月薪,部门名称等

 

select e.empno, e.ename, e.sal, d.dname
from emp e, dept d
where e.deptno = d.deptno

 

不等值连接

示例:
查询员工信息,员工号,姓名,月薪,薪水级别

 

select e.empno, e.ename, e.sal, s.grade
from emp e, salgrade s
where e.sal >= s.losal and e.sal <= s.hisal

 

或者

 

select e.empno, e.ename, e.sal, s.grade
from emp e, salgrade s
where e.sal between s.losal and s.hisal

 

外连接

eg:按部门统计员工人数:部门号 部门名称 各部门人数

 

select d.deptno,d.dname, count(e.empno)
from dept d, emp e
where d.deptno = e.deptno
group by d.deptno , d.dname

 


运行结果并没有部门编号为 40 的部门没有被显示出现
此时需要使用到外连接

select d.deptno,d.dname, count(e.empno)
from dept d, emp e
where d.deptno = e.deptno(+)
group by d.deptno , d.dname    

 

这是左外连接:(+)写在等号右侧。
作用是在连接条件不成立的情况下,也能把等号左边的数据给显示出来

 

select deptno, avg(sal)
from emp
having deptno = 10
group by deptno

 

posted @ 2020-06-20 11:12  王清河  阅读(227)  评论(0编辑  收藏  举报