我可以在另一个listagg查询的where子句中使用一个listagg查询的输出吗

时间:2018-07-13 05:47:13

标签: sql oracle plsql

我已经用listagg编写了如下查询

DECLARE
   v_data    VARCHAR2 (100);
   v_data2   VARCHAR2 (100);
BEGIN
   SELECT LISTAGG (data1, ',') WITHIN GROUP (ORDER BY data1)
     INTO v_data
     FROM table1
    WHERE data1 IN (1, 2, 3);

   DBMS_OUTPUT.put_line (v_data);

   SELECT LISTAGG (data2, ',') WITHIN GROUP (ORDER BY data2)
     INTO v_data2
     FROM table1
    WHERE data1 IN (v_data);

   DBMS_OUTPUT.put_line (v_data2);
END;

我可以在另一个listagg查询的where子句中使用一个listagg查询的输出吗?

v_data的输出为1,2,3,因此我想在第二个查询中使用它,例如where data in (v_data),即where data in(1,2,3)

与上述代码一样,我正在获取v_data的输出,而不是v_data2的输出。

2 个答案:

答案 0 :(得分:2)

基本上,应该将逗号分隔的值 V_DATA分成几行。

这是一个基于斯科特模式的示例:

SQL> DECLARE
  2     v_data    VARCHAR2 (100);
  3     v_data2   VARCHAR2 (100);
  4  BEGIN
  5     SELECT LISTAGG (deptno, ',') WITHIN GROUP (ORDER BY deptno)
  6       INTO v_data
  7       FROM dept
  8      WHERE deptno IN (10, 20, 30);
  9
 10     DBMS_OUTPUT.put_line (v_data);
 11
 12     SELECT LISTAGG (ename, ',') WITHIN GROUP (ORDER BY deptno)
 13       INTO v_data2
 14       FROM emp
 15      WHERE deptno IN (select regexp_substr(v_data, '[^,]+', 1, level)
 16                       from dual
 17                       connect by level <= regexp_count(v_data, ',') + 1
 18                      );
 19
 20     DBMS_OUTPUT.put_line (v_data2);
 21  END;
 22  /
10,20,30
CLARK,KING,MILLER,ADAMS,FORD,JONES,SCOTT,SMITH,ALLEN,BLAKE,JAMES,MARTIN,TURNER,WARD

PL/SQL procedure successfully completed.

SQL>

答案 1 :(得分:2)

好吧,从示例查询中还不清楚您为什么要第一个LISTAGG

基本上,这就是您要尝试做的事情:

   SELECT LISTAGG (data2, ',') WITHIN GROUP (ORDER BY data2)
     INTO v_data2
     FROM table1
    WHERE data1 IN ( select data1 from table1  where .. );--some other where clause