共用方式為


通用 table 表示式(CTE)

適用於:核取記號為「是」Databricks SQL 核取記號為「是」Databricks Runtime

定義暫存結果 set,您可以在 SQL 語句的範圍內參考可能多次。 CTE 主要用於 SELECT 語句。

語法

WITH common_table_expression [, ...]

common_table_expression
  view_identifier [ ( column_identifier [, ...] ) ] [ AS ] ( query )

Parameters

  • view_identifier

    以 identifier 參考 common_table_expression

  • column_identifier

    可選的 identifier,用於參考 common_table_expression 的 column。

    如果指定了 column_identifier,則其數目必須符合 query所傳回的 columns 數目。 如果未指定名稱,則 column 名稱衍生自 query

  • query

    查詢產生結果 set。

範例

-- CTE with multiple column aliases
> WITH t(x, y) AS (SELECT 1, 2)
  SELECT * FROM t WHERE x = 1 AND y = 2;
   1   2

-- CTE in CTE definition
> WITH t AS (
    WITH t2 AS (SELECT 1)
    SELECT * FROM t2)
  SELECT * FROM t;
   1

-- CTE in subquery
> SELECT max(c) FROM (
    WITH t(c) AS (SELECT 1)
    SELECT * FROM t);
      1

-- CTE in subquery expression
> SELECT (WITH t AS (SELECT 1)
          SELECT * FROM t);
                1

-- CTE in CREATE VIEW statement
> CREATE VIEW v AS
    WITH t(a, b, c, d) AS (SELECT 1, 2, 3, 4)
    SELECT * FROM t;
> SELECT * FROM v;
   1   2   3   4

-- CTE names are scoped
> WITH t  AS (SELECT 1),
       t2 AS (
        WITH t AS (SELECT 2)
        SELECT * FROM t)
SELECT * FROM t2;
   2