簡體   English   中英

SQL:兩個表的多個CTE的並集

[英]SQL: Union of two tables multiple CTEs

我的目標是在SQL中with table as alias兩個表,其中每個表都很復雜,並且必須使用with table as alias語法定義自己的公用表表達式。

因此,我們有了具有以下語法的第一個表:

with table1 as (
select/from/where statement),

table2 as (
select/from where statement),

select table1 join table2 on [...]

第二張表,具有類似的語法:

with table3 as (
select/from/where statement),

table4 as (
select/from where statement),

select table3 join table4 on [...]

我的問題是:簡單地把union這兩個表之間不剪 編譯器將上面兩個表之間的union視為錯誤的表達式。

(我的另一種方法是將整個第一個表定義為table5,將整個第二個表定義為table6,之后再將它們合並,這是因為您似乎無法將多個“ with as”語句相互堆疊。)

您必須將所有CTE放在第一個SELECT之前,但是然后可以像對待表一樣對其進行UNION:

WITH Table1 AS (..)
, Table2 AS (..)
, Table3 AS (..)
, Table4 AS (..)
SELECT Table1 JOIN Table2..
UNION 
SELECT Table3 JOIN Table4..

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM