데이터 분석/지표 분석
매출 분석 - 카테고리별 매출 구하기
중급닌자 연습생
2022. 12. 13. 23:53
카테고리별 매출이 얼마나 되는지 알고 싶어요
각 카테고리 내에서 차지하는 비율까지 알 수 있으면 좋겠어요
필요한 데이터
주문 상세 데이터(1차 카테고리, 2차 카테고리, 금액, 상품명)
풀이
select
category,
sub_category,
sum(price) over (partition by category, sub_category) amount,
sum(price) over (partition by category) total,
sum(price) over (partition by category, sub_category) / sum(price) over (partition by category) * 100 as rate
from purchase_detail_log
group by category, sub_category
✔ amount : 2차 카테고리 매출의 합
✔ total: 1차 카테고리 매출의 합
✔ rate: 1차 카테고리 매출 대비 2차 카테고리 매출의 비율
다른 풀이
select
coalesce(category, 'all') as category,
coalesce(sub_category, 'all') as sub_category,
sum(price) as amount
from purchase_detail_log
group by category, sub_category with rollup
✔ Coalesce() : category 값이 있으면 category, 없으면 'all'
✔ with rollup: {category 와 sub_category}에 대한 합계
데이터 출처: 데이터 분석을 위한 SQL 레시피