+---------------+---------+
|Column Name |Type|+---------------+---------+
| product_id | int || start_date | date || end_date | date || price | int |+---------------+---------+
(product_id, start_date, end_date) is the primarykey (combination of columns withuniquevalues) for this table.
Eachrowof this table indicates the price of the product_id in the period from start_date to end_date.
Foreach 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
1
2
3
4
5
6
7
8
9
+---------------+---------+
|Column Name |Type|+---------------+---------+
| product_id | int || purchase_date | date || units | int |+---------------+---------+
This table may contain duplicate rows.
Eachrowof this table indicates the date, units, and product_id ofeach 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.
To find the average selling price for each product, we need to join the Prices and UnitsSold tables on product_id and ensure the purchase_date falls within the price’s date range. We then calculate the total revenue and total units for each product, and divide to get the average price, rounding to 2 decimal places. If a product has no sales, its average price is 0.
SELECT p.product_id,
ROUND(COALESCE(SUM(u.units * p.price) /NULLIF(SUM(u.units), 0), 0), 2) AS average_price
FROM Prices p
LEFTJOIN UnitsSold u
ON p.product_id = u.product_id
AND u.purchase_date BETWEEN p.start_date AND p.end_date
GROUPBY p.product_id;