sql - 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 数据库。谢谢
解决方案
您可以尝试以下方法:
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 ..
添加了子句。
推荐阅读
- java - Intellij 无法解析文件/目录
- c++ - C++ 算术运算符是否能够在自定义类中进行积极优化?
- java - Java Spring CRUD 存储库方法“deleteById”不起作用
- cordova - 离子错误[运行子进程cordova时发生错误。]
- django - Django 模型大写
- javascript - 如何将值分配给reactjs中的contenteditable div
- javascript - ES6 按唯一属性过滤对象
- php - 如何获取商店清单产品WC WP中每一项的产品ID
- android - 如何将设备连接到 Xamarin.Forms 项目?
- javascript - 在 JavaScript 中将 Math.cos 函数的度数转换为弧度的问题