본문 바로가기

코딩일기

SQL 코드카타 125 - List the Products Ordered in a Period

https://leetcode.com/problems/list-the-products-ordered-in-a-period/description/

 

Column Name Type
product_id int
product_name varchar
product_category varchar

 

Products 테이블:

  • product_id : 테이블의 고유 키
  • product_name : 제품의 이름
  • product_category : 제품의 종류

 

Column Name Type
product_id int
order_date date
unit int

 

Products 테이블:

  • product_id : 테이블의 고유 키
  • order_date : 제품이 주문된 일자
  • unit : 주문된 제품의 수량

2020년 2월에 최소 100개 이상 주문된 제품들의 이름과 수량을 가져오세요.

 

select *
from Orders
group by date_format(order_date, '%Y%m')

 

Orders 테이블에서 order_date의 년, 월을 기준으로 그룹화한다.

 

select
    product_id,
    sum(unit) unit
from Orders
group by date_format(order_date, '%Y%m'), product_id

 

product_id도 그룹화 조건으로 추가한 뒤 product_id별 unit 의 합계를 구한다.

 

select
    product_id,
    date_format(order_date, '%Y%m') year_and_month,
    sum(unit) unit
from Orders
group by date_format(order_date, '%Y%m'), product_id
having year_and_month = 202002

 

having를 사용해서 2020년 02월의 데이터만 출력한다.

 

select *
from Products p
left join (select
    product_id,
    date_format(order_date, '%Y%m') year_and_month,
    sum(unit) unit
from Orders
group by date_format(order_date, '%Y%m'), product_id
having year_and_month = 202002) s on p.product_id = s.product_id

 

제품의 이름을 구하기 위해서 Priducts 테이블과 결합한다.

 

select  
    p.product_name,
    s.unit
from Products p
left join (select
    product_id,
    date_format(order_date, '%Y%m') year_and_month,
    sum(unit) unit
from Orders
group by date_format(order_date, '%Y%m'), product_id
having year_and_month = 202002) s on p.product_id = s.product_id
where s.unit >= 100

 

필요한 데이터를 고르고 unit이 100이상인 데이터만 출력하면 완료!

 

성공!