02/29 SQL 문제풀이 - 1164. Product Price at a Given Date (Leetcode)⭐⭐

Data Architect / Engineer·2024년 2월 29일
1

1일_1SQL

목록 보기
42/63
post-thumbnail

문제

  • LeetCode SQL 문제
  • 1164. Product Price at a Given Date / Medium
  • 문제 내용 : [링크]


내가 작성한 Query

with temp_01 as(
    select distinct product_id
    from products
),
temp_02 as(
    select product_id, max(change_date) as change_date
    from products
    where change_date <= '2019-08-16'
    group by product_id
),
temp_03 as(
select a.product_id, b.change_date
from temp_01 a
    left join temp_02 b on a.product_id = b.product_id
)
select a.product_id, coalesce(b.new_price, 10) as price
from temp_03 a
    left join products b on a.product_id=b.product_id and a.change_date=b.change_date 
  • temp_01distinct product_id를 통해 모든 제품 id 데이터를 저장

  • temp_02WHERE절에 change_date <= 2019-08-16 조건을 주고, product_idGROUP BY 해준다.

  • 이후, max(change_date) 값을 구해준다. 즉, '2019-08-16' 이전 데이터 중 가장 최근의 가격 변화가 일어난 날짜를 구해주는 과정이다.
    다만, '2019-08-16' 이전에 가격 변화가 없는 product_id가 있을 수 있다.

  • temp_01temp_02JOIN 해 준다. 이 때, 위에서 말했듯, '2019-08-16' 이전에 가격변동이 일어나지 않은 product_id도 포함이 되어야 하므로, temp_01의 데이터 레벨이 모두 출력되도록 LEFT JOIN 해 준다. 이 테이블을 temp_03으로 정의한다.

  • temp_03 테이블과 products 테이블을 LEFT JOIN해준다. LEFT JOIN 기준은 product_idchange_date가 같을 때를 조건으로 정해준다.

  • coalesce(b.new_price, 10) as price를 통해, '2019-08-16' 이전에 가격변동이 없던 제품들의 null 값을 기본값 10으로 출력되게 해 준다.

⭐⭐ JOIN 출력 데이터 레벨을 항상 고려해서 쿼리 작성할 것!

업로드중..

profile
질문은 계속돼 아오에

0개의 댓글