Oracle
 sql >> Base de Dados >  >> RDS >> Oracle

Pivot dinâmico no Oracle sql - Procedimento


Se você tiver uma tabela na qual deseja inserir os resultados do pivô toda vez que chamar o Stored Proc, poderá usar isso:
CREATE OR REPLACE PROCEDURE dynamic_pivot
AS
  v_sql LONG       := NULL;
  v_statement LONG := NULL;
BEGIN
  SELECT DISTINCT LISTAGG(''''
    || myLetter
    || ''' AS '
    || myLetter,',') WITHIN GROUP (
  ORDER BY myLetter) AS temp_in_statement
  INTO v_statement
  FROM
    (SELECT DISTINCT myLetter FROM test_data
    );
  v_sql := 'insert into pivot_table    
      select * from (SELECT myNumber, myLetter, myValue FROM test_data    
      )    
      PIVOT    
      (      
      SUM(myValue) AS val FOR myLetter IN (' || v_statement || ')    
      )';
  EXECUTE immediate v_sql;
END;