SQL

pivot 테이블 만들기

content0474 2024. 9. 2. 14:21

pivot table: 여러 데이터 중 원하는 데이터만 뽑아서 행과 열에 배치하여 만든 테이블

구조

select 열1, 열2, 열3, 열4

from 테이블 또는 서브쿼리문

group by 행

 

10대-50대까지 연령대별로 음식 종류마다 주문한 횟수를 보여주는 피벗 테이블

10대-50대까지 연령을 case when문으로 나누고, count함수로 주문 개수를 센 다음

위의 것을 서브쿼리문에 넣고 쿼리문에서는 열을 지정해준다

SELECT fo.cuisine_type,
              case when age between 10 and 19 then 10
                       when age between 20 and 29 then 20
                      when age between 30 and 39 then 30
                      when age BETWEEN 40 and 49 then 40
                      when age BETWEEN 50 and 59 then 50 end age,
              COUNT(1) cnt_order
10대-50대까지 연령을 나눠서 10-19세는 10, 20-29는 20, 30-39는 30, 40-49는 40, 50-59는 50으로 새로 이름을 붙이고 이 case when문 전체를 age라고 이름붙임

주문건수를 세기 위한 count 함수
FROM food_orders fo inner join customers c on fo.customer_id =c.customer_id 음식타입과 연령 정보를 이용하기 위해 두 테이블을 합침
where age between 10 and 59 10대-50대 연령만 사용해야 하므로 where절로 조건을 줬다. 이 조건을 주지 않으면 60대, 70대 등의 나이가 null로 처리되어 결과에 나타남
group by 1, 2 함수를 썼을때는 항상 group by 사용할 것

 

SELECT cuisine_type,
             max(if(age=10, cnt_order, 0))"10대",
             max(if(age=20, cnt_order, 0))"20대",
             max(if(age=30, cnt_order, 0))"30대",
             max(if(age=40, cnt_order, 0))"40대",
             max(if(age=50, cnt_order, 0))"50대"
이렇게 하면 피벗테이블의 열 이름이 각각 cuisine_type, 10대, 20대, 30대, 40대, 50대로 나온다.
max(if(age=10, cnt_order, 0))
: 서브쿼리의 case when문을 age라고 이름을 줬었는데, 이 age가 10이면 (when age between 10 and 19 then 10) cnt_order값을 적고, 아니면 0
FROM
(
SELECT fo.cuisine_type,
   case when age between 10 and 19 then 10
            when age between 20 and 29 then 20
            when age between 30 and 39 then 30
            when age between 40 and 49 then 40
            when age between 50 and 59 then 50 end age,
     COUNT(1) cnt_order
FROM food_orders fo inner join customers c on fo.customer_id =c.customer_id
where age between 10 and 59
group by 1, 2
)a
위에서 완성한 서브쿼리문
group by 1 이렇게 하면 행이 cuisine type별로 그룹지어져서 나온다