oracle sql 中的动态透视 - 过程

问题描述 投票:0回答:2

我从这个post得到了动态枢轴的解决方案。 现在我想在 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));

提前致谢。

sql oracle stored-procedures oracle11g pivot
2个回答
5
投票

如果您有一个表,想要在每次调用存储过程时插入数据透视表结果,则可以使用以下命令:

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;

0
投票

我在尝试创建基于 PIVOT 的表时遇到一些问题并给我错误代码

ORA-00921:SQL 命令意外结束我的 var 是 Lv_sql clob;当执行 立即执行 Lv_Query ;

© www.soinside.com 2019 - 2024. All rights reserved.