Dynamic pivot in oracle sql

后端 未结 7 967

... pivot (sum(A) for B in (X))

Now B is of datatype varchar2 and X is a string of varchar2 values separated by commas.
Values for X are select distinct values

7条回答
  •  无人及你
    2020-11-22 00:24

    You cannot put a dynamic statement in the PIVOT's IN statement without using PIVOT XML, but you can use small Technic to use dynamic statement in PIVOT. In PL/SQL, within a string value, two apostrophe is equal to one apostrophes.

    declare
      sqlqry clob;   
      search_ids  varchar(256) := '''2016'',''2017'',''2018'',''2019''';
    begin
      search_ids := concat( search_ids,'''2020''' ); -- you can append new search id dynamically as you wanted
      sqlqry :=
      '      
      select * from
      (
          select *
          from EMPLOYEE
      )
      pivot
      (
        MIN(QTY) for YR in (' || search_ids   || ')
      )';
    
      execute immediate sqlqry;
    end;
    

提交回复
热议问题