데이터 분석/SQL

[엑셀보다 빠른 SQL] 5-5 Window 함수 (이거 다시 풀어봐야 함)

경 민 2025. 2. 11. 18:33

Q. 각 음식점의 주문 건수가 해당 음식 타입에서 차지하는 비율을 구하고, 주문 건수 오름차순으로 누적 합 구하기


1단계 : 음식 타입&음식점별 주문 건수 구하기

 

select cuisine_type,
		restaurant_name,
		count(1) cnt_order
from food_orders
group by 1,2

 

2단계 : 1단계 테이블을 서브쿼리로 만들어서 음식 타입별 주문 건수 합계, 음식 타입별 주문 건수 누적합 구하기
SELECT cuisine_type,
		restaurant_name,
		cnt_order,
		sum(cnt_order) over (partition by cuisine_type) sum_cuisine,
		sum(a.cnt_order) over (partition by cuisine_type order by cnt_order) cum_cuisine
from
(
select cuisine_type,
		restaurant_name,
		count(1) cnt_order
from food_orders
group by 1,2
)
order by cuisine_type, cnt_order

 

🔶 이해 안 가는 부분

 

sum(cnt_order) over (partition by cuisine_type) sum_cuisine

: 음식 타입별 주문 건수의 총합계

 

sum(a.cnt_orderover (partition by cuisine_type order by cnt_ordercum_cuisine

: 음식 타입별 주문 건수 누적합 (주문 건수 오름차순으로 정렬했을 때)

 

order by 차이로 뭐가 달라지는 거지.

 

+ 마지막 ordery by 절에서 어떤 걸 추가해야 누적 합계가 정상적으로 나오는 것일까.

각 음식점을 정확하게 분류하기 위해 음식타입 + 식당 이름 을 기준으로 조회하라고 해서 restaurant_name을 추가했는데 아무런 변화가 없다.