[SQL Test] 지역별 주문의 특징 (예시를 통한 설명)

아리엘 (Ariel)·2025년 1월 12일
1

SQL Test

목록 보기
8/9

지역별 주문의 특징


📌 문제
https://solvesql.com/problems/characteristics-of-orders/

  • region, category 별 주문량을 출력
  • region 기준으로 오름차순 정렬

📌 정답

select region as Region,
  count(distinct(case when category like 'Furniture' then order_id end)) as 'Furniture',
  count(distinct(case when category like 'Office Supplies' then order_id end)) as 'Office Supplies',
  count(distinct(case when category like 'Technology' then order_id end)) as 'Technology'
from records
group by region
order by region

❎ 시행착오

select region as Region,
  sum(case when category like 'Furniture' then 1 else 0 end) as 'Furniture',
  sum(case when category like 'Office Supplies' then 1 else 0 end) as 'Office Supplies',
  sum(case when category like 'Technology' then 1 else 0 end) as 'Technology'
from records
group by region
order by region

💡포인트

  • 문제에서는 주문량(얼마나 많은 주문이 이루어졌는지)을 요구한다.
  • 주문량은 주문 번호(order_id) 기준으로 계산해야 한다.
  • 시행착오에서는 항목 수량(각 제품이 얼마나 팔렸는지)를 계산했기에 오류가 발생했다.

이해를 돕기 위해, 아래와 같은 데이터가 있을 때

order_idcategoryquantity
1001Furniture1
1001Office Supplies2
1002Technology1

주문량은 3개이다.

Furniture: 주문 번호 1001 → 1개의 주문
Office Supplies: 주문 번호 1001 → 1개의 주문
Technology: 주문 번호 1002 → 1개의 주문


항목 수량은 4개이다.

Furniture: 1개
Office Supplies: 2개
Technology: 1개

이렇듯, 주문량과 항목 수량이 달라질 수 있기 때문에 주문 번호를 기준으로 중복을 제거해야 한다.




💡 질문과 피드백 사항은 댓글에 편하게 남겨주시기 바랍니다.
❤️ 도움이 되셨다면 공감 부탁드립니다.

profile
Data Analyst / Engineer

0개의 댓글