반응형
문제
Write a solution to find the prices of all products on 2019-08-16.
Assume the price of all products before any change is 10.
Return the result table in any order.
The result format is in the following example.
문제 요약
2019-08-16 이 날, 모든 제품의 가격을 추출하라.
단, 모든 가격의 변경 이전 가격은 10이라고 가정
풀이
1. change_date가 '2019-08-16' 이전인 제품들만 추린 후, 거기서 MAX(change_date)의 가격 추출
2. 나머지 change_date가 '2019-08-16' 이후인 제품들만 추린 후, 그 제품의 가격은 10으로 고정
WITH t AS(SELECT *, RANK() OVER(
PARTITION BY product_id
ORDER BY change_date DESC
) rnk
FROM products
WHERE change_date <= '2019-08-16'
)
SELECT product_id, new_price AS price
FROM t
WHERE rnk = 1
UNION
SELECT product_id, 10 AS price
FROM products
WHERE product_id NOT IN(SELECT product_id FROM t)
배운 점
엄청 간단한 조건인데, 되게 돌고 돌아 생각한 것 같다.
닥친 문제가 어려울 수록, 조건을 간단하고 간결하게(개수가 적게) 설정해보자
반응형