Product Price At A Given Date Problem
Description
LeetCode Problem 1164.
Table: Products
+---------------+---------+
| Column Name | Type |
+---------------+---------+
| product_id | int |
| new_price | int |
| change_date | date |
+---------------+---------+
(product_id, change_date) is the primary key 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 an SQL query to find the prices of all products on 2019-08-16. Assume the price of all products before any change is 10.
The query result format is in the following example:
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 |
+------------+-----------+-------------+
Result table:
+------------+-------+
| product_id | price |
+------------+-------+
| 2 | 50 |
| 1 | 35 |
| 3 | 10 |
+------------+-------+
Solution
Approach: Last Change by the Date, Default 10
The price of a product on 2019-08-16 is the new_price of its last change on or before that day. A change made on 2019-08-16 itself counts (product 1 costs 35). If the product has no change by then, its price is still the starting price, 10.
- In a CTE, keep the changes with
change_date <= '2019-08-16'and number each product's changes from newest to oldest withROW_NUMBER(). Row 1 is the last change by that date.(product_id, change_date)is the primary key, so a product has no two changes on one day. - Take every product once (
SELECT DISTINCT product_id) andLEFT JOINits row 1. A product whose first change comes later, like product 3, has no row 1, soIFNULL(l.new_price, 10)gives 10.
Starting from the distinct products is what keeps product 3 in the result; filtering the dates in WHERE on the whole query would lose it.
The Pandas version keeps the changes up to the date, takes each product's last one with drop_duplicates(keep="last") after sorting by date, and maps those prices onto all products with 10 as the default.
WITH latest_change AS (
SELECT product_id,
new_price,
-- 1 = the last change on or before 2019-08-16.
ROW_NUMBER() OVER (PARTITION BY product_id ORDER BY change_date DESC) AS rn
FROM Products
WHERE change_date <= '2019-08-16'
)
SELECT p.product_id,
IFNULL(l.new_price, 10) AS price
FROM (
SELECT DISTINCT product_id
FROM Products
) AS p
LEFT JOIN latest_change AS l
ON l.product_id = p.product_id
AND l.rn = 1;
Now write it from memory
Close the write-up and solve it yourself against the tests.