[LeetCode] 1164. Product Price at a Given Date - SQL

Donghyun·2024년 9월 10일
0

Code Kata - SQL

목록 보기
61/61
post-thumbnail

링크: https://leetcode.com/problems/product-price-at-a-given-date/

Table: Products

+---------------+---------+
| Column Name   | Type    |
+---------------+---------+
| product_id    | int     |
| new_price     | int     |
| change_date   | date    |
+---------------+---------+
(product_id, change_date) is the primary key (combination of columns with unique values) of this table.
Each row of this table indicates that the price of some product was changed to a new price at some date.

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.

Example 1:

Input:
Products table:
+------------+-----------+-------------+
| product_id | new_price | change_date |
+------------+-----------+-------------+
| 1          | 20        | 2019-08-14  |
| 2          | 50        | 2019-08-14  |
| 1          | 30        | 2019-08-15  |
| 1          | 35        | 2019-08-16  |
| 2          | 65        | 2019-08-17  |
| 3          | 20        | 2019-08-18  |
+------------+-----------+-------------+
Output:
+------------+-------+
| product_id | price |
+------------+-------+
| 2          | 50    |
| 1          | 35    |
| 3          | 10    |
+------------+-------+

문제풀이

목표: 2019-08-16에 모든 제품들의 가격을 찾는 솔루션 작성.

  • 변화 전 가격은 모두 10이라고 가정

최종코드

SELECT product_id, new_price AS price
FROM Products
WHERE change_date <= '2019-08-16'
  AND (product_id, change_date) IN (
      SELECT product_id, MAX(change_date)
      FROM Products
      WHERE change_date <= '2019-08-16'
      GROUP BY product_id
  )

UNION

SELECT product_id, 10 AS price
FROM Products
WHERE product_id NOT IN (
    SELECT product_id
    FROM Products
    WHERE change_date <= '2019-08-16'
);

설명

첫 번째 SELECT 쿼리

SELECT product_id, new_price AS price
FROM Products
WHERE change_date <= '2019-08-16'
  AND (product_id, change_date) IN (
      SELECT product_id, MAX(change_date)
      FROM Products
      WHERE change_date <= '2019-08-16'
      GROUP BY product_id
  )
  • 2019-08-16일 이전에 가격이 변경된 제품들 중에서, 가장 최근의 가격을 가져오는 쿼리.
  • 서브쿼리를 사용하여 각 product_id에 대해 가장 최근의 change_date를 찾고,
  • 그 날짜에 해당하는 new_price를 가져온다.

두 번째 SELECT 쿼리

SELECT 
	product_id, 
	10 AS price
FROM Products
WHERE product_id NOT IN (
    SELECT product_id
    FROM Products
    WHERE change_date <= '2019-08-16'
);
  • 2019-08-16 이전에 가격이 한 번도 변경되지 않은 제품에 대해 기본 가격 10을 반환.
  • NOT IN을 사용하여 2019-08-16 이전에 한 번도 가격이 변경된 적이 없는 product_id들을 필터링

이 결과들을 UNION으로 결합하여, 가격이 변경된 제품들은 최신 가격을 가져오고, 변경되지 않은 제품들은 기본 가격 10을 반환하게 된다.

profile
데이터분석 공부 일기~!

0개의 댓글