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 |
+------------+-------+
with tmp as
(select product_id, new_price as price,
row_number() over (partition by product_id order by change_date desc) num
from products
where change_date <= '2019-08-16')
select product_id, price
from tmp
where num = 1
union
select product_id, 10 as price
from (select distinct product_id
from products
where change_date > '2019-08-16'
and product_id not in (select distinct product_id from tmp)) t2
SELECT A.product_id,
CASE WHEN M.new_price IS NULL THEN 10 ELSE M.new_price END AS 'price'
FROM
(SELECT DISTINCT product_id FROM Products) A
LEFT JOIN
(SELECT product_id, new_price,
ROW_NUMBER() OVER (PARTITION BY product_id ORDER BY change_date DESC) AS 'rnk'
FROM Products
WHERE change_date <= '2019-08-16') M
ON A.product_id = M.product_id
WHERE rnk = 1 OR rnk IS NULL