two columns Pivoting in Oracle SQL -
i have question in pivoting data in oracle . here data looks
id, taskname, type, date 44400 m0 1/1/2015 44400 m1 1/3/2015 44400 m2 1/4/2015 44400 m1 cf 2/1/2105 44400 dg1 cf 2/2/2015 44400 m0 por 2/11/2015 45000 m0 2/1/2015 45000 m1 2/3/2015 45000 m2 2/4/2015 45000 m1 cf 3/1/2105 45000 dg1 cf 3/2/2015 45000 m0 por 3/11/2015
and want pivot above data , need in below form dynamically.
now, want data below
id m0_a m1_a m2_a m1_cf dg1_cf m0_por 44400 1/1/2015 1/3/2015 1/4/2015 2/1/2015 2/2/2015 2/11/2015 45000 2/1/2015 2/3/2015 2/4/2015 3/1/2015 3/2/2015 3/11/2015
i appreciate help. in advance.
for defined number of pairs of values in columns tname, ttype
can use below query (note changed column names example, because used oracle keywords there, named table tasks
, have change data real column names , table name everywhere in code) :
select * tasks pivot (max(tdate) (tname, ttype) in (('dg1','cf') dg1_cf, ('m0','a') m0_a, ('m0','por') m0_por, ('m1','a' ) m1_a, ('m1','cf') m1_cf, ('m2','a') m2_a)));
for dynamic number of possibilities need procedure "creating" query. here used view
this. copy procedure code , compile it. when data in table changes have run procedure @ first, select view created procedure. in order run schema needs privilleges creating views granted.
execute create_tasks_view; select * v_tasks; anonymous block completed id dg1_cf m0_a m0_por m1_a m1_cf m2_a ----- ---------- ---------- ---------- ---------- ---------- ---------- 45000 2015-03-02 2015-02-01 2015-03-11 2015-02-03 2015-03-01 2015-02-04 44400 2015-02-02 2015-01-01 2015-02-11 2015-01-03 2015-02-01 2015-01-04
of course can change ordering of rows , columns wish adding or modifying order by
parts in procedure code:
create or replace procedure create_tasks_view v_sql varchar2(32767) := ''; begin v in (select distinct tname, ttype tasks order tname, ttype) loop v_sql := v_sql || '(''' || v.tname || ''',''' || v.ttype || ''') ' ||v.tname||'_'||v.ttype||','; end loop; v_sql := 'create or replace view v_tasks ' ||'select * tasks pivot (max(tdate) (tname, ttype) in (' ||rtrim(v_sql, ', ')||'))'; execute immediate v_sql; end create_tasks_view;
i believe there more universal solution question in link gave in comments: dynamic sql pivoting.... looks promising, read section resources @ bottom, , follow steps of instruction. didn't check method personally, maybe suit more "procedure-view" solution.
Comments
Post a Comment