본문 바로가기

Back-End/Database

[Oracle] decode를 이용한 데이터 행열 변환




 select 

      empno 

 from emp

 where rownum<=4;


 ROWNUM

 EMPNO 

 1 

 7369

 2 

 7499 

 3

 7521

 4

 7566 





 select 

      max(decode(rownum, 1, empno)) as emp1,

      max(decode(rownum, 2, empno)) as emp2

      max(decode(rownum, 3, empno)) as emp3

      max(decode(rownum, 4, empno)) as emp4

 from emp

 where rownum<=4;



 EMP1

 EMP2 

 EMP3 

 EMP4 

 7369

 7499 

 7521 

 7566



select

    decode(level,1,x.emp1, 2,x.emp2, 3,x.emp3, 4,x.emp4) as result

from

(

    select

        max(decode(rownum, 1, empno)) as emp1,

        

        max(decode(rownum, 2, empno)) as emp2,

        max(decode(rownum, 3, empno)) as emp3,

        max(decode(rownum, 4, empno)) as emp4

    from emp

    where rownum<=4

)x, dual


connect by level<=4;