我从这篇文章中找到了解决动态枢轴问题的方法。现在,我想在oracle过程中实现以下语句。
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));
提前致谢。
如果您有一个表,希望在每次调用“存储过程”时插入数据透视表结果,则可以使用以下方法:
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;