카테고리 없음

엑셀보다 쉽고 빠른 SQL - 5주차

gamzaa914 2025. 4. 29. 17:32

 

5주차



 

 

1. SQL로 피벗 테이블 만들기

  • 피벗테이블이란? 2개 이상의 기준으로 데이터를 집계할 때, 보기 쉽게 배열하여 보여주는 것을 의미합니다.

 

  ex) 음식점별, 시간별 주문건수 피벗 테이블 뷰 만들기(15~20시 사이, 20시 주문건수 기준 내림차순)

SELECT restaurant_name,
	   max(if(hh='15', cnt_order, 0)) "15시",
	   max(if(hh='16', cnt_order, 0)) "16시",
	   max(if(hh='17', cnt_order, 0)) "17시",
	   max(if(hh='18', cnt_order, 0)) "18시",
	   max(if(hh='19', cnt_order, 0)) "19시",
	   max(if(hh='20', cnt_order, 0)) "20시"
FROM 
(
select f.restaurant_name,
	   substr(p.time, 1, 2) hh,
	   COUNT(1) cnt_order
from food_orders f inner JOIN  payments p on f.order_id = p.order_id
where substr(p.time, 1, 2) between 15 and 20
group by 1, 2
) a
group by 1
order by 7 desc

▲ 20시 기준으로 내림차순 정렬이 됨

 

 

  ex) 성별, 연령별 주문건수 피벗테이블 뷰 만들기(나이는 10~59세 사이, 연령 순으로 내림차순)

select age,
	   max(if(gender='male', order_count, 0)) 'male',
	   max(if(gender='female', order_count, 0)) 'female'
from
(
select c.gender,
	   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) order_count
from food_orders f inner join customers c on f.customer_id = c.customer_id
where c.age between 10 and 59
group by 1, 2
) a
group by 1
order by age

 

2. Window Function - Rank, Sum

window_function() over(patition by 그룹 기준 칼럼 order by 정렬 기준)

 

 

  ex) 음식 타입별로 주문 건수가 가장 많은 상점 3개씩 조회하기(음식 타입별, 순위별로 정렬하기)

select cuisine_type,
	   restaurant_name,
	   order_count,
	   rn "순위"
FROM
(
select cuisine_type,
	   restaurant_name,
	   rank() over(partition by cuisine_type order by order_count desc) rn,
	   order_count
from
(
select cuisine_type,
	   restaurant_name,
	   count(1) order_count
from food_orders
group by 1, 2
) a
) b
where rn <= 3
order by 1, 4

 

 

오늘은 SQL구문이 길었다.

길이가 긴 만큼 쉼표나 오탈자 들이 많아서 에러도 많이 떴는데 에러를 찾아서 고치는 재미도 있는 것 같다..!