diff --git a/README.md b/README.md index 0f4e640..0addebd 100644 --- a/README.md +++ b/README.md @@ -55,6 +55,7 @@ Have a good contributing! - [1141. User Activity for the Past 30 Days I](./leetcode/easy/1141.%20User%20Activity%20for%20the%20Past%2030%20Days%20I.sql) - [1148. Article Views I](./leetcode/easy/1148.%20Article%20Views%20I.sql) - [1211. Queries Quality and Percentage](./leetcode/easy/1211.%20Queries%20Quality%20and%20Percentage.sql) + - [1251. Average Selling Price](./leetcode/easy/1251.%20Average%20Selling%20Price.sql) - [1327. List the Products Ordered in a Period](./leetcode/easy/1327.%20List%20the%20Products%20Ordered%20in%20a%20Period.sql) - [1378. Replace Employee ID With The Unique Identifier](./leetcode/easy/1378.%20Replace%20Employee%20ID%20With%20The%20Unique%20Identifier.sql) - [1407. Top Travellers](./leetcode/easy/1407.%20Top%20Travellers.sql) diff --git a/leetcode/easy/1251. Average Selling Price.sql b/leetcode/easy/1251. Average Selling Price.sql new file mode 100644 index 0000000..7f01b4f --- /dev/null +++ b/leetcode/easy/1251. Average Selling Price.sql @@ -0,0 +1,47 @@ +/* +Question 1251. Average Selling Price +Link: https://leetcode.com/problems/average-selling-price/description/?envType=study-plan-v2&envId=top-sql-50 + +Table: Prices + ++---------------+---------+ +| Column Name | Type | ++---------------+---------+ +| product_id | int | +| start_date | date | +| end_date | date | +| price | int | ++---------------+---------+ +(product_id, start_date, end_date) is the primary key (combination of columns with unique values) for this table. +Each row of this table indicates the price of the product_id in the period from start_date to end_date. +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. + + +Table: UnitsSold + ++---------------+---------+ +| Column Name | Type | ++---------------+---------+ +| product_id | int | +| purchase_date | date | +| units | int | ++---------------+---------+ +This table may contain duplicate rows. +Each row of this table indicates the date, units, and product_id of each product sold. + + +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. + +Return the result table in any order. +*/ + +SELECT + p.product_id, + COALESCE(ROUND(SUM(p.price * u.units) * 1.00 / SUM(u.units), 2), 0.00) AS average_price +FROM Prices AS p +LEFT JOIN + UnitsSold AS u + ON + p.product_id = u.product_id + AND u.purchase_date BETWEEN p.start_date AND p.end_date +GROUP BY p.product_id