subquery_factoring_clause
The WITH
query_name
clause lets you assign a name to a subquery block. You can then reference the subquery block multiple places in the query by specifying the query name. Oracle Database optimizes the query by treating the query name as either an inline view or as a temporary table.
You can specify this clause in any top-level SELECT
statement and in most types of subqueries. The query name is visible to the main query and to all subsequent subqueries except the subquery that defines the query name itself.
Restrictions on Subquery Factoring This clause is subject to the following restrictions:
You can specify only one
subquery_factoring_clause
in a single SQL statement. You cannot specify aquery_name
in its own subquery. However, anyquery_name
defined in thesubquery_factoring_clause
can be used in any subsequent named query block in thesubquery_factoring_clause
.In a compound query with set operators, you cannot use the
query_name
for any of the component queries, but you can use thequery_name
in theFROM
clause of any of the component queries.
oracle 给出的一个示例:
Subquery Factoring: Example The following statement creates the query names dept_costs
and avg_cost
for the initial query block containing a join, and then uses the query names in the body of the main query.
WITH dept_costs AS ( SELECT department_name, SUM(salary) dept_total FROM employees e, departments d WHERE e.department_id = d.department_id GROUP BY department_name), avg_cost AS ( SELECT SUM(dept_total)/COUNT(*) avg FROM dept_costs) SELECT * FROM dept_costs WHERE dept_total > (SELECT avg FROM avg_cost) ORDER BY department_name;