본문 바로가기
오라클

[Oracle] 오라클 UNPIVOT()에 대해서

by eyesmin 2023. 12. 21.

오라클 UNPIVOT()에 대해서

 

오라클 unpivot

 

 

오라클의 UNPIVOT은 행과 열을 변환하여 열의 값을 행으로 전환하는 쿼리입니다.

기존의 가로 데이터를 세로 데이터로 변환하는 역할을 합니다.

 

SELECT *

FROM ( 테이블 )

UNPIVOT (칼럼 1 FOR 칼럼 2 IN (세로로 출력할 컬럼, 세로로 출력할 컬럼...));

 

*컬럼 1 = 데이터

*컴럼 2 = 칼럼명

 

 

다음은 간단한 예시입니다

 

select COUNTRY, CAPITAL, NUM
from (
select '대한민국' as country, '서울' as capital, '82' num from dual union all
select '미국' as country, '워싱턴' as capital, '1' num from dual union all
select '영국' as country, '런던' as capital, '44' num from dual union all
select '일본' as country, '도쿄' as capital, '81' num from dual
);

 

asis

 

 

UNPIVOT()을 사용하여 가로로 출력된 데이터를 country칼럼을 기준으로 하여 세로로 출력하겠습니다.

 

select COUNTRY, information, val from
(
select '대한민국' as country, '서울' as capital, '82' num from dual union all
select '미국' as country, '워싱턴' as capital, '1' num from dual union all
select '영국' as country, '런던' as capital, '44' num from dual union all
select '일본' as country, '도쿄' as capital, '81' num from dual
) unpivot (val for information in( CAPITAL, NUM ));

 

tobe

 

 

위 데이터를 보시면 UNPIVOT을 사용하여 데이터가 가로로 출력되는 것을 확인할 수 있습니다.

capita와 num컬럼이 컬럼 2의 information로 적용되어 세로로 출력되었으며,

그에 맞게 val 지정한 컬럼1에 데이터가 출력되었습니다.