Skip to content

Commit 8ea98d6

Browse files
authored
Solved -> 1164. Product Price at a Given Date
1 parent 59acf90 commit 8ea98d6

File tree

1 file changed

+71
-0
lines changed

1 file changed

+71
-0
lines changed
Lines changed: 71 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,71 @@
1+
/*
2+
3+
Problem Link -> https://leetcode.com/problems/product-price-at-a-given-date/description/?envType=study-plan-v2&envId=top-sql-50
4+
5+
------------------------------------------------------------- QUESTION -----------------------------------------------------------
6+
7+
Table: Products
8+
9+
+---------------+---------+
10+
| Column Name | Type |
11+
+---------------+---------+
12+
| product_id | int |
13+
| new_price | int |
14+
| change_date | date |
15+
+---------------+---------+
16+
(product_id, change_date) is the primary key (combination of columns with unique values) of this table.
17+
Each row of this table indicates that the price of some product was changed to a new price at some date.
18+
19+
20+
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.
21+
Return the result table in any order.
22+
The result format is in the following example.
23+
24+
25+
Example 1:
26+
27+
Input:
28+
Products table:
29+
+------------+-----------+-------------+
30+
| product_id | new_price | change_date |
31+
+------------+-----------+-------------+
32+
| 1 | 20 | 2019-08-14 |
33+
| 2 | 50 | 2019-08-14 |
34+
| 1 | 30 | 2019-08-15 |
35+
| 1 | 35 | 2019-08-16 |
36+
| 2 | 65 | 2019-08-17 |
37+
| 3 | 20 | 2019-08-18 |
38+
+------------+-----------+-------------+
39+
40+
Output:
41+
+------------+-------+
42+
| product_id | price |
43+
+------------+-------+
44+
| 2 | 50 |
45+
| 1 | 35 |
46+
| 3 | 10 |
47+
+------------+-------+
48+
49+
*/
50+
51+
-- ----------------------------------------------------------- SOLUTION -----------------------------------------------------------
52+
53+
SELECT product_id, new_price AS price
54+
FROM Products
55+
WHERE (product_id, change_date) IN
56+
(
57+
SELECT product_id, max(change_date)
58+
FROM Products
59+
WHERE change_date <= '2019-08-16'
60+
GROUP BY product_id
61+
)
62+
UNION
63+
SELECT product_id, 10 AS price
64+
FROM Products
65+
WHERE product_id NOT IN
66+
(
67+
SELECT product_id
68+
FROM Products
69+
WHERE change_date <= '2019-08-16'
70+
)
71+

0 commit comments

Comments
 (0)