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_order) over (partition by cuisine_type order by cnt_order) cum_cuisine
: 음식 타입별 주문 건수 누적합 (주문 건수 오름차순으로 정렬했을 때)
order by 차이로 뭐가 달라지는 거지.
+ 마지막 ordery by 절에서 어떤 걸 추가해야 누적 합계가 정상적으로 나오는 것일까.
각 음식점을 정확하게 분류하기 위해 음식타입 + 식당 이름 을 기준으로 조회하라고 해서 restaurant_name을 추가했는데 아무런 변화가 없다.

'데이터 분석 > SQL' 카테고리의 다른 글
| [day2] SQL - 상위 n개 데이터 구하기 'Limit' (0) | 2025.02.18 |
|---|---|
| [달리기반 SQL] 6번 문제 (0) | 2025.02.13 |
| [SQL] WHERE / HAVING 차이 정리 (0) | 2025.02.13 |
| [달리기반 SQL] 4번 문제 (0) | 2025.02.12 |
| [걷기반 SQL] 마지막 연습 문제 톺아보기 (0) | 2025.02.12 |