LeetCode - 1164. Product Price at a Given Date (MySQL)

조민수·2024년 6월 23일
0

LeetCode

목록 보기
43/61

Medium, SQL - UNION

RunTime : 435 ms


문제

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일 기준 이전의 price값 중 최신값을 가져오는 문제, 값이 없으면 10

풀이

  • 어려웠음, 해답 참조함
  • UNION이전 상단 : 2019-08-16이전에 가격 변경이 없는 product_id에 대해 10으로 값을 매겨 가져옴
  • 이후 하단 : 2019-08-16이전에 가격 변경이 있는 제품에 대해 가장 최신의 가격을 가져옴
    • WHERE change_date <= '2019-08-16'MAX(change_date)로 가져오기 떄문
SELECT DISTINCT product_id, 10 as price FROM Products
GROUP BY 1
HAVING MIN(change_date) > '2019-08-16'

UNION

SELECT product_id, new_price FROM Products
WHERE (product_id, change_date) IN
(
    SELECT product_id, MAX(change_date) as recent_date FROM Products
    WHERE change_date <= '2019-08-16'
    GROUP BY 1
)
profile
사람을 좋아하는 Front-End 개발자

0개의 댓글