Oracle 하위 쿼리 연결
하위 쿼리 :
다른 SQL 문에 중첩 된 전체 SQL 문을 하위 쿼리라고 할 수 있습니다.
분류:
단일 행 하위 쿼리
다중 행 하위 쿼리
-- 有哪些人的薪水是整个雇员的平均薪水之上的
-- 1.先求平均薪水
select avg(sal)
from EMP;
-- 2.把每个人薪水与平均薪水进行比较
select EMPNO, ENAME, SAL
from EMP
where SAL > (select avg(sal)
from EMP);
-- 1.雇员中哪些人是经理人
select distinct e.MGR
from emp e;
-- 2.查询雇员中的经理人
select EMPNO, ENAME
from EMP
where EMPNO in (select distinct e.MGR
from emp e);
-- 每个部门的平均薪水等级
-- 1.先求每个部门的平均薪水等级
select e.DEPTNO, avg(SAL)
from EMP e
group by e.DEPTNO;
-- 2.与薪水等级表做关联 查询等级
select t.DEPTNO, sal.GRADE
from (select e.DEPTNO, avg(SAL) sal
from EMP e
group by e.DEPTNO) t
join SALGRADE sal on t.sal between sal.LOSAL and sal.HISAL;
-- 求平均薪水最高的部门部门编号
-- 1.求部门的平均薪水
select e.DEPTNO, avg(SAL) sal
from EMP e
group by e.DEPTNO;
-- 就平均薪水最高的
select max(sal)
from (select e.DEPTNO, avg(SAL) sal
from EMP e
group by e.DEPTNO);
-- 求最高平均薪水的部门
select DEPTNO
from (select e.DEPTNO, avg(SAL) sal
from EMP e
group by e.DEPTNO) t
where t.sal = (select max(sal)
from (select e.DEPTNO, avg(SAL) sal
from EMP e
group by e.DEPTNO));
-- 求部门每个人的薪水等级
select e.DEPTNO, sg.GRADE
from EMP e
join SALGRADE sg
on e.SAL between sg.LOSAL and sg.HISAL;
-- 按照部门去平均等级
select t.DEPTNO, avg(t.GRADE)
from (select e.DEPTNO, sg.GRADE
from EMP e
join SALGRADE sg
on e.SAL between sg.LOSAL and sg.HISAL) t
group by t.DEPTNO;
-- 限制输出,limit,mysql中用来做限制输出的,但是oracle中不是
-- 再oracle中,如果需要做限制输出和分页的话需要使用rownum
-- 但是rownum不能直接使用,需要嵌套使用
-- 4,求薪水最高的前5名雇员
select *
from (select * from emp order by sal desc)
where ROWNUM <= 5;
-- 先查询5条然后在排序
select *
from EMP
where ROWNUM <= 5
order by SAL desc;
-- 使用rownum的时候必须要在外层添加嵌套,此时才能将rownum作为其中一个列,然后再进行限制输出
-- 查询薪资排名6-10员工
select *
from (select * from emp order by SAL desc)
where ROWNUM > 5
and ROWNUM <= 10;
-- 查询前10雇员
select t1.*,ROWNUM
from (select * from emp order by SAL desc) t1
where ROWNUM <= 10;
select *
from (select t1.*, ROWNUM rn
from (select * from emp order by SAL desc) t1
where ROWNUM <= 10) t
where t.rn > 5
and t.rn <= 10;
select *
from (select t1.*, ROWNUM rn
from (select * from emp order by SAL desc) t1
) t
where t.rn > 5
and t.rn <= 10;