-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathproductPriceatDate1164.sql
More file actions
60 lines (53 loc) · 1.82 KB
/
productPriceatDate1164.sql
File metadata and controls
60 lines (53 loc) · 1.82 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
/*
1164. Product Price at a Given Date: https://leetcode.com/problems/product-price-at-a-given-date/description/
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.
Return the result table in any order.
The query 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 |
+------------+-------+
*/
# 1. This solution requires getting the closest date to '2019-08-16' by using a window function.
# 2. Do a union statement for all IDs that had am order date above '2019-08-16'
# beats 46% runtime:
with t as (SELECT product_id, new_price, change_date,
row_number() OVER (PARTITION BY product_id ORDER BY change_date DESC) as rn
FROM products
WHERE change_date <= '2019-08-16')
SELECT product_id, new_price as price
FROM t
WHERE rn=1
UNION
SELECT product_id, 10
FROM products
WHERE product_id NOT IN (
SELECT product_id
FROM t)