<aside> 💡
This project focuses on calculating the average selling price of products based on their sales data and historical pricing. The task demonstrates advanced SQL skills, including joining multiple tables, handling date ranges, and aggregating data.
</aside>
product_id, start_date, end_date).The objective was to calculate the average selling price for each product, defined as the total revenue divided by the total units sold, rounded to two decimal places. If no units are sold for a product, its average selling price should be 0.
The query joins the Prices and UnitsSold tables, ensuring alignment based on date ranges. It calculates the weighted average selling price using SQL's aggregate functions.
SELECT
p.product_id,
IFNULL(ROUND(SUM(p.price * us.units) / SUM(us.units), 2), 0) AS average_price
FROM
Prices p
LEFT JOIN
UnitsSold us
ON
p.product_id = us.product_id
AND us.purchase_date BETWEEN p.start_date AND p.end_date
GROUP BY
p.product_id;
LEFT JOIN ensures that all products in the Prices table are included, even if there are no matching entries in the UnitsSold table.us.purchase_date BETWEEN p.start_date AND p.end_date links sales data to the corresponding pricing period.SUM(p.price * us.units) calculates the total revenue for each product by multiplying the price with the number of units sold during each pricing period.SUM(us.units) computes the total number of units sold for each product.ROUND(SUM(p.price * us.units) / SUM(us.units), 2) calculates the weighted average selling price, rounded to two decimal places.IFNULL(..., 0) handles cases where no units are sold, ensuring the average price is set to 0.GROUP BY p.product_id ensures the calculations are performed separately for each product.