与cte union一起选择进入

时间:2018-07-18 14:43:56

标签: sql amazon-redshift

我正在尝试执行以下操作:

with cte as (
select ...
from ....
)

select ... 
from cte

union all

with cte2 as (
select ...
from ....
)

select ... 
into table --
from cte2

我以前可能曾宣誓这样做过,但是现在我遇到了Invalid operation: syntax error at or near "with"错误。这样写是不可能的,还是我想念其他东西?

我知道我可以这样写:

with cte as (
select ...
from ....
),
with cte2 as (
select ...
from ....
)

select ... 
from cte

union all

select ... 
into table --
from cte2

但是我尝试不这样做,因为cte和cte2中的数据来自不同的合作伙伴,所以我更愿意将每个合作伙伴的with cte asselect from cte保持在一起。

1 个答案:

答案 0 :(得分:1)

多CTE时,您只需要删除with ,

它看起来像:

with cte as (
  select 1 id
),cte2 as (
  select 2 id
)
,cte3 as (
  select * from CTE
  union all
  select * from CTE2
)
insert into T select * from CTE3;

结果:

| id |
|----|
|  1 |
|  2 |

测试DDL:

CREATE TABLE T
    (id int)
;

结果:

| ID |
|----|
|  1 |
|  2 |

SQL Fiddle