본문 바로가기

Study/Oracle

Oracle : 열을 행으로 변환 (max 함수)

반응형

CREATE TABLE TEMP
(
  DATA1  VARCHAR2(10),
  DATA2  VARCHAR2(10),
  DATA3  VARCHAR2(10),
  DATA4  VARCHAR2(10),
  DATA5  VARCHAR2(10),
  DATA6  VARCHAR2(10)

Insert into UMSDB.TEMP   (DATA1, DATA2, DATA3, DATA4, DATA5, DATA6) Values   ('A', '1', '1', '1', '사과  ', '수박');
Insert into UMSDB.TEMP   (DATA1, DATA2, DATA3, DATA4, DATA5, DATA6) Values   ('A', '1', '2', '1', '배    ', '수박');
Insert into UMSDB.TEMP   (DATA1, DATA2, DATA3, DATA4, DATA5, DATA6) Values   ('A', '1', '3', '1', '바나나', '수박');
Insert into UMSDB.TEMP   (DATA1, DATA2, DATA3, DATA4, DATA5, DATA6) Values   ('A', '1', '3', '2', '귤    ', '수박');
Insert into UMSDB.TEMP   (DATA1, DATA2, DATA3, DATA4, DATA5, DATA6) Values   ('A', '1', '3', '3', '귤2   ', '수박');
Insert into UMSDB.TEMP   (DATA1, DATA2, DATA3, DATA4, DATA5, DATA6) Values   ('A', '1', '3', '4', '귤1   ', '수박');
 

SELECT 
     A.DATA1,A.DATA2,A.DATA3,
     MAX(DECODE(R-R1,0,DATA5))MINOR1,
     MAX(DECODE(R-R1,0,DATA6))MINOR2,
     MAX(DECODE(R-R1,1,DATA5))MINOR3,
     MAX(DECODE(R-R1,1,DATA6))MINOR4,
     MAX(DECODE(R-R1,2,DATA5))MINOR5,
     MAX(DECODE(R-R1,2,DATA6))MINOR6,
     MAX(DECODE(R-R1,3,DATA5))MINOR7,
     MAX(DECODE(R-R1,3,DATA6))MINOR8
FROM (SELECT 
                ROWNUM R, DATA1, DATA2, DATA3, DATA4, DATA5, DATA6
           FROM TEMP) A,
           (SELECT 
                MIN(ROWNUM)R1, DATA1, DATA2, DATA3
            FROM TEMP GROUP BY DATA1, DATA2, DATA3) B
WHERE A.DATA1 = B.DATA1
    AND A.DATA2 = B.DATA2 
    AND A.DATA3 = B.DATA3
GROUP BY A.DATA1, A.DATA2, A.DATA3

" MAX(DECODE(R-R1,행의수,DATA5))MINOR||행의수  " 를 추가


출처 : http://jmkjb.tistory.com/entry/columntorow

반응형