본문 바로가기
데이터 분석/SQL과 Python

[SQL] 가로 세로 피봇팅 하기

2022. 12. 17.

피봇팅은 행(의 값)을 열로 변환하는 것을 의미한다

→ 열로 변환되므로 그룹함수를 활용하고 데이터를 집계하는데 유용!

풀이

select
	dt,
	max(case when indicator = 'impressions' then val end) as impressions,
	max(case when indicator = 'sessions' then val end) as sessions,
	max(case when indicator = 'users' then val end) as users
from daily_kpi
group by dt

 case 문으로 새로운 레이블의 컬럼을 지정해주면서
 case 문의 결과는 [10]과 같은 리스트 형식이기 때문에 하나의 스칼라(값)을 추출하기 위해 max나 min 함수와 같은 집계 함수를 사용함

before
after

피봇팅 연습하기

 

Occupations (HackerRank)

Occupations | HackerRank Pivot the Occupation column so the Name of each person in OCCUPATIONS is displayed underneath their respective Occupation. www.hackerrank.com Pivot the Occupation column in OCCUPATIONS so that each Name is sorted alphabetically and

hyeyun133.tistory.com

 

댓글