링크: 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
에 모든 제품들의 가격을 찾는 솔루션 작성.
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을 반환하게 된다.