首页 > 解决方案 > Redshift - 使用嵌套查询的输出作为另一个查询的输入

问题描述

我有一个嵌套查询,就像

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 数据库。谢谢

标签: sqlamazon-redshiftnested-queries

解决方案


您可以尝试以下方法:

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

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


推荐阅读