<aside> 💡

Project Overview:

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>


Problem Description:

Tables:

  1. Prices:
  2. UnitsSold:

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.


Solution:

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;


Explanation:

  1. Joining Tables:
  2. Revenue Calculation:
  3. Units Sold Calculation:
  4. Average Selling Price:
  5. Grouping:

Example Input and Output: