Skip to content

Commit 276016f

Browse files
committed
task: #1251
1 parent 7a2bcd4 commit 276016f

File tree

2 files changed

+48
-0
lines changed

2 files changed

+48
-0
lines changed

README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -55,6 +55,7 @@ Have a good contributing!
5555
- [1141. User Activity for the Past 30 Days I](./leetcode/easy/1141.%20User%20Activity%20for%20the%20Past%2030%20Days%20I.sql)
5656
- [1148. Article Views I](./leetcode/easy/1148.%20Article%20Views%20I.sql)
5757
- [1211. Queries Quality and Percentage](./leetcode/easy/1211.%20Queries%20Quality%20and%20Percentage.sql)
58+
- [1251. Average Selling Price](./leetcode/easy/1251.%20Average%20Selling%20Price.sql)
5859
- [1327. List the Products Ordered in a Period](./leetcode/easy/1327.%20List%20the%20Products%20Ordered%20in%20a%20Period.sql)
5960
- [1378. Replace Employee ID With The Unique Identifier](./leetcode/easy/1378.%20Replace%20Employee%20ID%20With%20The%20Unique%20Identifier.sql)
6061
- [1407. Top Travellers](./leetcode/easy/1407.%20Top%20Travellers.sql)
Lines changed: 47 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,47 @@
1+
/*
2+
Question 1251. Average Selling Price
3+
Link: https://leetcode.com/problems/average-selling-price/description/?envType=study-plan-v2&envId=top-sql-50
4+
5+
Table: Prices
6+
7+
+---------------+---------+
8+
| Column Name | Type |
9+
+---------------+---------+
10+
| product_id | int |
11+
| start_date | date |
12+
| end_date | date |
13+
| price | int |
14+
+---------------+---------+
15+
(product_id, start_date, end_date) is the primary key (combination of columns with unique values) for this table.
16+
Each row of this table indicates the price of the product_id in the period from start_date to end_date.
17+
For each product_id there will be no two overlapping periods. That means there will be no two intersecting periods for the same product_id.
18+
19+
20+
Table: UnitsSold
21+
22+
+---------------+---------+
23+
| Column Name | Type |
24+
+---------------+---------+
25+
| product_id | int |
26+
| purchase_date | date |
27+
| units | int |
28+
+---------------+---------+
29+
This table may contain duplicate rows.
30+
Each row of this table indicates the date, units, and product_id of each product sold.
31+
32+
33+
Write a solution to find the average selling price for each product. average_price should be rounded to 2 decimal places. If a product does not have any sold units, its average selling price is assumed to be 0.
34+
35+
Return the result table in any order.
36+
*/
37+
38+
SELECT
39+
p.product_id,
40+
COALESCE(ROUND(SUM(p.price * u.units) * 1.00 / SUM(u.units), 2), 0.00) AS average_price
41+
FROM Prices AS p
42+
LEFT JOIN
43+
UnitsSold AS u
44+
ON
45+
p.product_id = u.product_id
46+
AND u.purchase_date BETWEEN p.start_date AND p.end_date
47+
GROUP BY p.product_id

0 commit comments

Comments
 (0)