Dynamic pivot in oracle sql

后端 未结 7 961

... pivot (sum(A) for B in (X))

Now B is of datatype varchar2 and X is a string of varchar2 values separated by commas.
Values for X are select distinct values

7条回答
  •  鱼传尺愫
    2020-11-22 00:31

    I am not exactly going to give answer for the question OP has asked, instead I will be just describing how dynamic pivot can be done.

    Here we have to use dynamic sql, by initially retrieving the column values into a variable and passing the variable inside dynamic sql.

    EXAMPLE

    Consider we have a table like below.

    If we need to show the values in the column YR as column names and the values in those columns from QTY, then we can use the below code.

    declare
      sqlqry clob;
      cols clob;
    begin
      select listagg('''' || YR || ''' as "' || YR || '"', ',') within group (order by YR)
      into   cols
      from   (select distinct YR from EMPLOYEE);
    
    
      sqlqry :=
      '      
      select * from
      (
          select *
          from EMPLOYEE
      )
      pivot
      (
        MIN(QTY) for YR in (' || cols  || ')
      )';
    
      execute immediate sqlqry;
    end;
    /
    

    RESULT

    If required, you can also create a temp table and do a select query in that temp table to see the results. Its simple, just add the CREATE TABLE TABLENAME AS in the above code.

    sqlqry :=
    '    
      CREATE TABLE TABLENAME AS
      select * from
    

提交回复
热议问题