使用WITH子句重用子查询
使用WITH子句重用子查询
从Oracle9i开始,通过WITH子句可以给子查询指定一个名称,并且使得在一条语句中可以完成所有任务,从而避免使用临时表。
如显示部门工资总和高于雇员工资总和三分之一的部门名称及工资总和。
WITH summary AS (SELECT dname,SUM(sal) AS dept_total
FROM emp,dept
WHERE emp.deptno=dept.deptno
GROUP BY dname)
SELECT dname, dept_total
FROM summary
WHERE dept_total>( SELECT SUM(dept_total) * 1/3 FROM summary);
使用WITH语句建立对工资求和并求平均值的可重用查询代码。
WITH
dept_sum AS (SELECT d.dname,sum(e.sal) total
FROM dept d, emp e
WHERE d.deptno=e.deptno
GROUP by d.dname),
dept_avg_sum AS (SELECT sum(total)/count(*) avg_sum FROM dept_sum)
其中,dept_sum和dept_avg_sum是被定义的两个子查询名字,引用方法如下:
SELECT dname,total FROM dept_sum
WHERE total>(SELECT avg_sum FROM dept_avg_sum)
运行结果为:
DNAME TOTAL
-------------- ---------- RESEARCH 13075