(해당 포스트는 Inflearn - [백문이불여일타] 데이터 분석을 위한 중급 SQL 강의록입니다.)
PIVOT이란 가로를 세로로, 세로를 가로로 만드는 것.
조금 있어보이게 표현하면 row와 column 값의 위치를 바꾸는 것이다.
집계함수인 Avg를 Group by절과 함께 사용 시
이미 평균 값을 한 컬럼 내에 정의할 수 있었다.
select Avg(quantity), user_id
from orders
group by user_id
위의 쿼리는 아래와 같은 값을 반환한다.
위와 같이 반환해도 보는데에는 문제가 크게 없지만 간혹 위처럼 종단으로 긴 데이터가 아니라 횡단으로 길게 늘어진 데이터가 필요할 수도 있다.
이를테면 아래 그림과 같다.
이렇게 데이터의 종, 횡을 바꾸는 것을
Pivoting이라고 하고, 이 Pivoting에는 많은 방법이 있지만 case문을 이용해서도 가능하다.
select avg(case when user_id=1 then quantity else null end) as user_1_q_avg,
avg(case when user_id=2 then quantity else null end) as user_2_q_avg,
avg(case when user_id=3 then quantity else null end) as user_3_q_avg,
avg(case when user_id=4 then quantity else null end) as user_4_q_avg,
avg(case when user_id=5 then quantity else null end) as user_5_q_avg,
avg(case when user_id=11 then quantity else null end) as user_11_q_avg,
avg(case when user_id=21 then quantity else null end) as user_21_q_avg,
avg(case when user_id=24 then quantity else null end) as user_24_q_avg
from orders;
이번에 회사에서 큰 프로젝트를 진행하며 실제로 이 기능이 필요했었던 것이 떠올랐다.
잘 숙지해두자.