在SQL中使用嵌套选择时,pivot不起作用

时间:2017-09-04 05:03:05

标签: sql oracle pivot

我需要透过用户指定的特定表的列。  问题是每个表到pivot的列数是动态的。 所以下面的代码从表中获取列的名称。

SELECT DISTINCT 
                LISTAGG('''' || column_name || '''', ',') 
                    WITHIN GROUP (ORDER BY column_name) AS temp_in_statement 
                FROM (SELECT DISTINCT column_name FROM all_tab_columns WHERE table_name = 'DIM_XYZ')

上面的代码以下列格式返回列:

col1, col2

我必须使用一个支点来满足这个要求,并在下面的代码中插入上面的代码,以便转动列。

SELECT * FROM
(
  SELECT table_name, column_name
  FROM ALL_TAB_COLUMNS
  WHERE
      table_name = 'DIM_XYZ'

)
PIVOT
(
  MIN(column_name)
  FOR column_name IN ( 

-- values added manually 

 'col1','col2'

-- values added manually 


    )
)
ORDER BY table_name;

在这种情况下代码可以正常工作,但在更换' col1',' col2'通过select语句检索列名称,系统抛出以下错误:

ORA-00936: missing expression
00936. 00000 -  "missing expression"
*Cause:    
*Action:
Error at Line: 39 Column: 40

CODE:

SELECT * FROM
(
  SELECT table_name, column_name
  FROM ALL_TAB_COLUMNS
  WHERE
      table_name = 'DIM_XYZ'

)
PIVOT
(
  MIN(column_name)
  FOR column_name IN ( 

--code below does not work when plugged in the statement above
              SELECT DISTINCT 
                LISTAGG('''' || column_name || '''', ',') 
                    WITHIN GROUP (ORDER BY column_name) AS temp_in_statement 
                FROM (SELECT DISTINCT column_name FROM all_tab_columns WHERE table_name = 'DIM_XYZ')
 --code above does not work
    )
)
ORDER BY table_name;
----------------

你们有任何想法如何解决这个问题吗?

1 个答案:

答案 0 :(得分:0)

您无法直接将动态表达式添加为数据透视表的输入, 您可以尝试这样的方法,我们通过PL / SQL块检索变量中表的所有列,然后以符合Oracle数据透视表功能的方式传递它。

SET serveroutput ON;


    DECLARE 
    sqlquery VARCHAR(32767);
    cols VARCHAR2(32767);
    BEGIN

      SELECT listagg('''' || column_name || '''',   ',') within
      GROUP(
      ORDER BY column_name)
      INTO cols
      FROM
        (SELECT DISTINCT column_name
         FROM all_tab_columns
         WHERE TABLE_NAME = 'TABLE_NAME')
      ;

      sqlquery := '      
    SELECT * FROM
    (
      SELECT table_name, column_name
      FROM ALL_TAB_COLUMNS
      WHERE
          table_name = ''TABLE_NAME''
    )
    PIVOT
    (
      MIN(column_name)
      FOR column_name IN ( 
            ''||cols||''
        )
      )
      ORDER BY table_name';

      DBMS_OUTPUT.PUT_LINE(sqlquery);

      EXECUTE IMMEDIATE sqlquery;

    END;
    /