Skip to content

1251. Average Selling Price

Problem Statement

Table: Prices

Column NameType
product_idint
start_datedate
end_datedate
priceint

(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 NameType
product_idint
purchase_datedate
unitsint

This table may contain duplicate rows.

Each row of this table indicates the date (purchase_date), units, and product_id of each product sold.

Instructions

  • Write a solution to find the average selling price for each product. average_price should be rounded to two (2) decimal places.
  • Return the result table in any order.
  • The result format is in the following example.

Example

Input:

Prices table

product_idstart_dateend_dateprice
12019-02-172019-02-285
12019-03-012019-03-2220
22019-02-012019-02-2015
22019-02-212019-03-3130

UnitsSold table

product_idpurchase_dateunits
12019-02-25100
12019-03-0115
22019-02-10200
22019-03-2230

Output:

product_idaverage_price
16.96
216.96

Explanation:

Average selling price = Total Price of ProductNumber of products sold.

Average selling price for product 1 is ((1005)+(1520))115=6.96.

Average selling price for product 2 is ((20015)+(3030))230=16.96

Submissions

sql
SELECT
    p.product_id,
    COALESCE(ROUND(SUM(u.units * p.price) / NULLIF(SUM(u.units), 0)::decimal, 2), 0) AS average_price
FROM
    Prices p
LEFT JOIN
    UnitsSold u ON u.product_id = p.product_id
                AND u.purchase_date BETWEEN p.start_date AND p.end_date
GROUP BY
    p.product_id;

Explanations

PostgreSQL
Submitted by @noeyislearning
  • SELECT p.product_id: Select the product_id from the Prices table.
    • COALESCE(ROUND(SUM(u.units * p.price) / NULLIF(SUM(u.units), 0)::decimal, 2), 0) AS average_price: Calculate the average_price for each product_id.
  • FROM Prices p: Select the Prices table and alias it as p.
  • LEFT JOIN UnitsSold u ON u.product_id = p.product_id AND u.purchase_date BETWEEN p.start_date AND p.end_date: Join the UnitsSold table with the Prices table on product_id and purchase_date between start_date and end_date.
  • GROUP BY p.product_id: Group the result by product_id.