DB 세로 데이터를 가로로 PIVOT 하는 것 질문드립니다. 0 4 2,237

by 열심히할께요 [2015.05.10 17:22:43]


WITH V1 AS (
SELECT 70 AS MASTER_SQ, 60 AS DETAIL_SQ FROM DUAL
UNION ALL
SELECT 70 AS MASTER_SQ, 61 AS DETAIL_SQ FROM DUAL
UNION ALL
SELECT 72 AS MASTER_SQ, 70 AS DETAIL_SQ FROM DUAL
UNION ALL
SELECT 72 AS MASTER_SQ, 71 AS DETAIL_SQ FROM DUAL
UNION ALL
SELECT 72 AS MASTER_SQ, 72 AS DETAIL_SQ FROM DUAL
)
SELECT * FROM V1

MASTER_SQ DETAIL_SQ
70 60
70 61
72 70
72 71
72 72

위와 같은 데이터가 있다고 가정 했을 때

MASTER_SQ DETAIL_SQ1 DETAIL_SQ2 DETAIL_SQ3
70 60 61  
72 70 71 72

와 같이 출력하고 싶습니다.(공부중입니다..)

 두가지 방법을 다 사용해보고 싶습니다.

하나는 PIVOT 함수를 사용하여 출력하고 싶고

하나는 DUAL을 사용하여 뽑고 싶습니다.

조언 부탁드립니다! ^^ 즐거운 주말 되세요

 

 

by 열심히할께요 [2015.05.10 17:48:05]

WITH V1 AS (
        SELECT 70 AS MASTER_SQ, 61 AS DETAIL_SQ FROM DUAL
        UNION ALL
        SELECT 70 AS MASTER_SQ, 60 AS DETAIL_SQ FROM DUAL
        UNION ALL
        SELECT 72 AS MASTER_SQ, 70 AS DETAIL_SQ FROM DUAL
        UNION ALL
        SELECT 72 AS MASTER_SQ, 71 AS DETAIL_SQ FROM DUAL
        UNION ALL
        SELECT 72 AS MASTER_SQ, 72 AS DETAIL_SQ FROM DUAL
)
SELECT
    MASTER_SQ,
    MIN(DECODE(RNUM, 1, DETAIL_SQ)) DATA1,
    MIN(DECODE(RNUM, 2, DETAIL_SQ)) DATA2,
    MIN(DECODE(RNUM, 3, DETAIL_SQ)) DATA3
 FROM(
        SELECT
         ROW_NUMBER() OVER(PARTITION BY MASTER_SQ ORDER BY V1.MASTER_SQ) RNUM,
         MASTER_SQ,
         DETAIL_SQ
        FROM V1
 )
 GROUP BY MASTER_SQ

자문 자답이지만

우선 PIVOT 을 사용하지 않고 뽑아봤습니다..


by 마농 [2015.05.11 02:37:16]

정렬 부분이 틀렸네요.

  - 오류 : ORDER BY V1.MASTER_SQ

  - 수정 : ORDER BY V1.DETAIL_SQ


by 마농 [2015.05.11 02:40:29]
SELECT *
  FROM (SELECT master_sq, detail_sq
             , ROW_NUMBER() OVER(PARTITION BY master_sq ORDER BY detail_sq) rn
          FROM v1
        )
 PIVOT (MIN(detail_sq) FOR rn IN (1 d1, 2 d2, 3 d3))
;

 


by 열심히할께요 [2015.05.13 08:59:24]

감사합니다^^

좋은 하루 되세요~

댓글등록
SQL문을 포맷에 맞게(깔끔하게) 등록하려면 code() 버튼을 클릭하여 작성 하시면 됩니다.
로그인 사용자만 댓글을 작성 할 수 있습니다. 로그인, 회원가입