oracle with 子查詢用法

jidongzheng發表於2009-04-07

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 a query_name in its own subquery. However, any query_name defined in the subquery_factoring_clause can be used in any subsequent named query block in the subquery_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 the query_name in the FROM clause of any of the component queries.

[@more@]

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;

來自 “ ITPUB部落格 ” ,連結:http://blog.itpub.net/197458/viewspace-1020053/,如需轉載,請註明出處,否則將追究法律責任。

相關文章