Oracle pivoting unknown number of column before execution time

。_饼干妹妹 提交于 2019-12-24 23:13:52

问题


I have something like this:

id  cod
1   a
1   b
1   c
2   d
2   e
3   f
3   g

and i need something like this:

id  cod 1   cod 2   cod 3
1   a       b       c
2   d       e   
3   f       g   

you understand that there is no way to know how many column oracle will have to generate before the execution time.


回答1:


You can use procedure p_pivot, code below. It dynamically builds view v_test based on your table. Then you can select from this view like here:

Connected to Oracle Database 10g Release 10.2.0.4.0 

SQL> execute p_pivot;

PL/SQL procedure successfully completed

SQL> select * from v_test;

        ID COD1  COD2  COD3
---------- ----- ----- -----
         1 a     b     c
         2 d     e     
         3 f     g     

Procedure (please change table name from test to your table name in code):

create or replace procedure p_pivot is
  v_cols number;
  v_sql varchar2(4000);
begin
  select max(cnt) into v_cols
    from (select count(1) cnt from test group by id);

  v_sql := 
  'create or replace view v_test as 
  with t as (select row_number() over (partition by id order by cod) rn, test.* from test)
  select id';

  for i in 1..v_cols
  loop
    v_sql := v_sql || ', max(decode(rn, '||i||', cod)) cod'||i;
  end loop;
  v_sql := v_sql || ' from t group by id';
  execute immediate v_sql;
end p_pivot;



回答2:


There is NO way how to do that. Oracle HAS to know the number of columns at the moment when it is compiling the query.

Imagine that you create a view using such a query. The view would have different number of columns each time you look at it.

Also there should be no way how to fetch data from such a query. Because you do not know how many columns have until you evaluate all the data in the table.




回答3:


Hi You can use this query also.

--Creating test data

create table test_me(id_num  number,val varchar2(10));

insert all 

into test_me 

values(1,'a')

into test_me values (1,'b')

into test_me values (1,'c')

into test_me values (2,'d')

into test_me values (2,'e')

into test_me values (3,'f')

into test_me values (3,'g')

select 1 from dual;

select * from 

(

select id_num,val,row_number() over (partition by  id_num order by val) rn

from test_me )

pivot (max(val) for id_num in(1 as val_1,2 as val_2,3 as val_3));

The SQLFiddle demo is here http://sqlfiddle.com/#!4/4206f/1



来源:https://stackoverflow.com/questions/29032037/oracle-pivoting-unknown-number-of-column-before-execution-time

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!