考虑查询
select listagg(''''||Name||'''', ',') within group (order by Name) from STUDENTS;
这使我的输出为
'Jon','Rob','Bran'
如何在内部查询中使用它,请考虑以下示例:
with lst as(
select listagg(''''||Name||'''', ',') within group (order by Name) as name_list from STUDENTS)
select * from result where Name in (select name_list from lst)
预期结果:
-----------------
| Name | Score |
-----------------
| Jon | 80 |
-----------------
| Rob | 60 |
-----------------
| Bran | 75 |
-----------------
但实际结果不会返回任何行,因为它将子查询视为单个字段。
如何处理?
答案 0 :(得分:1)
listagg
分析函数的输出是文本数据。因此,即使你认为你正在
'Jon','Rob','Bran'
作为输出,它实际上是一个单独的字符串,如
'''Jon'', ''Rob'', ''Bran'''
为了您的目的,@ artm的答案应该足够了。否则,如果您必须按照自己的意愿行事,那么您需要使用动态SQL,如下所示:
declare
p_cur sys_refcursor;
name_list clob;
select_sql clob;
begin
select listagg(''''||Name||'''', ',')
within group (order by Name) as name_list
into name_list
from STUDENTS;
select_sql := 'select * from result where name in (' || name_list || ')';
open p_cur for select_sql;
end;
/