File tree 1 file changed +71
-0
lines changed
05_Avanced_Select_and_Joins
1 file changed +71
-0
lines changed Original file line number Diff line number Diff line change
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
+
You can’t perform that action at this time.
0 commit comments