2

I got a solution to dynamic pivot from this post . Now I want to implement the below statements in an oracle procedure.

clear columns
COLUMN temp_in_statement new_value str_in_statement
SELECT DISTINCT 
LISTAGG('''' || myLetter || ''' AS ' || myLetter,',')
    WITHIN GROUP (ORDER BY myLetter) AS temp_in_statement 
FROM (SELECT DISTINCT myLetter FROM myTable);
SELECT * FROM 
(SELECT myNumber, myLetter, myValue FROM myTable)
PIVOT (Sum(myValue) AS val FOR myLetter IN (&str_in_statement));

Thanks in advance.

Community
  • 1
  • 1
Ram
  • 845
  • 1
  • 13
  • 26

1 Answers1

5

If you have a table you want to insert the pivot results each time you call the Stored Proc, you can use this:

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;
user2247364
  • 158
  • 1
  • 5
  • Thank you very much.. I have implemented this successfully :) +1vote for the quick response – Ram Feb 05 '17 at 10:42