본문 바로가기
SQL/SQL Grammar

[자동차 매출 데이터] 미국 베스트셀러 top 5 자동차 구하기 (서브쿼리)

by ISLA! 2023. 10. 5.

본 포스팅은 아래 도서의 내용을 스터디, 참고했습니다.

 

최종 쿼리와 결과

select * 
from (
	select *
		, row_number() over (order by sales desc) as ranking
    from    
		(select productName, sum(priceEach * quantityordered) as sales
		from orders as a
		left join orderdetails as b on a.orderNumber = b.orderNumber
		left join products as c on b.productCode = c.productCode
		left join customers as d on d.customerNumber = a.customerNumber
		where country = 'USA'
        group by 1) B
		) A
where ranking <= 5
order by ranking;

 

1단계 : 데이터셋 합쳐서, 베이스 데이터 도출

  • 국가 정보를 위해 customers 테이블을, 제품명 정보를 위해 products 테이블을, 매출액 계산을 위해 orders와 orderdetails 를 불러와 join 한다.
  • 미국 정보만 보기 위해 where 절을 쓴다.
  • group by 를 이용하여 제품별 총 매출을 합산한다.

 

2단계 : 매출액 기반으로 랭킹을 계산(서브쿼리 이용)

  • 앞단계에서 제품명과 매출액이 도출되었다. 이를 서브쿼리로 From 절에 넣고
  • select 절에서 row_number()로 랭킹을 매겨준다.

 

3단계 : 5 순위까지만 확인하기 위해 서브쿼리 이용

  • 결과를 ranking 기반으로 5순위까지 보려고 where 절을 활용하고 싶다.
  • 이를 위해 서브쿼리를 한 번 더 써준다

728x90