Redshift-使用嵌套查询的输出作为另一个查询的输入

时间:2018-09-21 11:58:56

标签: sql amazon-redshift nested-queries

我有一个类似

的嵌套查询
with q1 as (select * from table1), 
q2 as (select * from table2) 
select q1.col1, q2.col2,listagg(q1.id || ' - ' || q2.id, ', ') as unique_id  
from q1 join q2 on q1.id = q2.id;

我正在尝试使用从上述查询中获得的 unique_id 并查询另一个表。

任何人都可以指导我如何使用在上面的查询中创建的这个新列作为另一个查询的输入。谢谢

我正在使用Redshift DB。谢谢

1 个答案:

答案 0 :(得分:1)

您可以尝试以下方法:

create table table1(id int,col1 varchar(10));
create table table2(id int,col2 varchar(10));

insert into table1 values(1,'A');
insert into table1 values(2,'B');
insert into table2 values(1,'C');
insert into table2 values(2,'D');

with q(col1, col2, id1, id2) as
 (
  select q1.col1, q2.col2, q1.id as id1, q2.id as id2
  from table1 q1
  join table2 q2
    on q1.id = q2.id 
 )
select col1,col2,
       listagg(id1 || ' - ' || id2, ', ') within group ( order by id1 ) as unique_id
  from q
 group by col1,col2;

COL1    COL2    UNIQUE_ID
  A       C       1 - 1
  B       D       2 - 2

您需要像@Gordon所指出的那样添加group by,而listagg函数不能单独使用。因此,添加了within group ( order by ..子句。