OkBublewrap

1164. Product Price at a Given Date 본문

개발/SQL

1164. Product Price at a Given Date

옥뽁뽁 2025. 1. 24. 15:45

Product Price at a Given Date

문제

  1. product_idchange_date는 기본키(고유 값을 가지는 컬럼들의 조합)
  2. 2019-08-16에 모든 상품의 가격을 찾는 솔루션 작성
  3. 모든 상품의 초기 가격(변경 전)은 10 이라고 가정
  4. 2019-08-16 이전에 바뀐 이력이 있으면 그대로 출력, 없으면 10을 출력

입력 테이블

  1. Products
    • product_id
    • new_price
    • change_date

풀이

1. CTE

고유한 product_id한 테이블 생성

select distinct product_id
from Products

2. '2019-08-16' 이하인 데이터에서 해당 날짜에 가까운 값 생성 row_number()

row_number()을 사용하여 가까운 값 가져오기

select product_id, new_price, change_date,
    row_number() over (partition by product_id order by change_date desc) as rn
from Products 
where change_date <= '2019-08-16'

3. CTE 기준으로 LEFT JOIN 사용

'2019-08-16'에 가장 가까운 값 = 1으로 JOIN

select t1.product_id, coalesce(t2.new_price, 10) as price
from temp_01 t1
left join temp_02 t2 on t1.product_id = t2.product_id 
and t2.rn = 1

4. 전체 코드

with temp_01 as 
(
    select distinct product_id
    from Products
), temp_02 as (
    select product_id, new_price, change_date,
        row_number() over (partition by product_id order by change_date desc) as rn
    from Products 
    where change_date <= '2019-08-16'
)
select t1.product_id, coalesce(t2.new_price, 10) as price
from temp_01 t1
left join temp_02 t2 on t1.product_id = t2.product_id 
and t2.rn = 1

'개발 > SQL' 카테고리의 다른 글

1484. Group Sold Products By The Date  (0) 2025.02.01
Google Big Query(with 리눅스)  (0) 2025.01.25
180. Consecutive Numbers  (0) 2025.01.22
1070. Product Sales Analysis III  (0) 2025.01.22
1934. Confirmation Rate  (0) 2025.01.21