记得在考ocp的051考题,有道题目是说,根据员工表,求得工资在部门平均工资之上得员工,需要进行多表关联查询。
先要按部门求平均工资:
SQL> select deptno,avg(sal) as avg_sal_dpt from emp_copy group by deptno;
DEPTNO AVG_SAL_DPT
------ -----------
30 1566.666666
20 2223
10 2916.666666
SQL>
然后再关联原表,得出在平均工资之上的员工:
SQL> select t1.empno, t1.ename, t1.deptno, t1.sal, t2.avg_sal_dpt
2 from emp_copy t1,
3 (select deptno, avg(sal) as avg_sal_dpt from emp_copy group by deptno) t2
4 where t1.deptno = t2.deptno
5 and t1.sal >= t2.avg_sal_dpt;
EMPNO ENAME DEPTNO SAL AVG_SAL_DPT
----- ---------- ------ --------- -----------
7499 ALLEN 30 1600.00 1566.666666
7566 JONES 20 2975.00 2223
7698 BLAKE 30 2850.00 1566.666666
7788 SCOTT 20 3000.00 2223
7839 KING 10 5000.00 291