본문 바로가기

Oracle/SQL Question

[퀴즈] 행을 열로 변환 퀴즈

code      value

1            aaa

1            bbb

2            ccc

3            ddd

3            eee


 

=> 위 data를 아래의 형식으로

code         value1    value2

1               aaa          bbb

2               ccc

3               ddd           eee

=>정답 트리플 클릭
WITH T AS (
SELECT '1' AS CODE, 'AAA' AS VAL FROM DUAL UNION ALL
SELECT '1' AS CODE, 'BBB' AS VAL FROM DUAL UNION ALL
SELECT '2' AS CODE, 'CCC' AS VAL FROM DUAL UNION ALL
SELECT '3' AS CODE, 'DDD' AS VAL FROM DUAL UNION ALL
SELECT '3' AS CODE, 'EEE' AS VAL FROM DUAL
)
SELECT CODE,
       MIN(DECODE(SEQ,1,VAL)),
       MIN(DECODE(SEQ,2,VAL))
FROM (
      SELECT CODE ,ROW_NUMBER() OVER(PARTITION BY CODE ORDER BY CODE) SEQ,VAL
      FROM T
      )
GROUP BY CODE