Oracle
 sql >> Database >  >> RDS >> Oracle

Pivot dinamico in Oracle sql - Procedura

Se hai una tabella in cui desideri inserire i risultati pivot ogni volta che chiami Stored Proc, puoi utilizzare questo:

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;