Thursday, May 1, 2014

example of using pivot in Oracle

--example of using pivot in Oracle
create table XXTMHR.test
(COL1 varchar2(100), COL2 varchar2(100));


insert into XXTMHR.test values(1, 101);
insert into XXTMHR.test values(1, 102);
insert into XXTMHR.test values(1, 103);
insert into XXTMHR.test values(1, 104);
insert into XXTMHR.test values(1, 105);
insert into XXTMHR.test values(2, 102);
insert into XXTMHR.test values(2, 104);
insert into XXTMHR.test values(2, 105);


--option 1
select col1
       , max(decode(seq,1,col2,null)) A1
       , max(decode(seq,2,col2,null)) A2
       , max(decode(seq,3,col2,null)) A3
       , max(decode(seq,4,col2,null)) A4
       , max(decode(seq,5,col2,null)) A5
from
(
select   col1
           , col2
           , row_number() over
            ( PARTITION BY col1
              order by col2 asc NULLS LAST) seq
     from XXTMHR.test) temp
group by temp.col1

--option 2
select * from
 (select   col1
            , col2
            , row_number() over
            ( PARTITION BY col1
              order by col2 asc NULLS LAST) seq
        from XXTMHR.test) temp
pivot(
       max (col2) for seq in (1,2,3,4,5)
       )

No comments:

Post a Comment