Oracle高階查詢案例
阿新 • • 發佈:2018-10-31
1、分頁查詢
--查詢員工表中(5,8]頁的記錄 select rownum,r,empno,ename,sal from ( select rownum r , empno,ename,sal from (select rownum,empno,ename,sal from emp order by sal desc) e1 where rownum<=8) e2 where r > 5
2.查詢員工表中薪水大於本部門平均薪水的員工
--多表查詢 select e.empno,e.ename,e.sal,d.avgsal from emp e,(select deptno,avg(sal) avgsal from emp group by deptno) d where e.deptno = d.deptno and e.sal>d.avgsal select * from table(dbms_xplan.display)
--相關子查詢 select empno,ename,sal,(select avg(sal) avgsal from emp where deptno = e.deptno) from emp e where sal > ( select avg(sal) avgsal from emp where deptno = e.deptno )
注意:在SQL語句前加 explain plan for
explain plan for select e.empno,e.ename,e.sal,d.avgsal from emp e,(select deptno,avg(sal) avgsal from emp group by deptno) d where e.deptno = d.deptno and e.sal>d.avgsal
再執行命令 select * from table(dbms_xplan.display) 檢視兩種方法的資源佔用大小。最後對比發現,相關子查詢更好
3、統計每個年份入職員工人數的和
--方法一 函式 select count(*) total , sum(decode(to_char(hiredate,'YYYY'),'1980',1,0)) "1980", sum(decode(to_char(hiredate,'YYYY'),'1981',1,0)) "1981", sum(decode(to_char(hiredate,'YYYY'),'1982',1,0)) "1982", sum(decode(to_char(hiredate,'YYYY'),'1987',1,0)) "1987" from emp; --方法二 select (select count(*) from emp) Total, (select count(*) from emp where to_char(hiredate,'YYYY')='1980') "1980" , (select count(*) from emp where to_char(hiredate,'YYYY')='1981') "1981" , (select count(*) from emp where to_char(hiredate,'YYYY')='1982') "1982" , (select count(*) from emp where to_char(hiredate,'YYYY')='1987') "1987" from dual;
--慕課學習筆記