Dataford
Interview QuestionsInterview GuidesExperiencesMock InterviewsPricing
Get started

SQL Average Selling Price

MediumSQL · PostgreSQL00:00
Practice interviewer
In session
5 left
00:00

Your question is SQL Average Selling Price. Start with the requirements and the two tables on the right.

Run and submit as often as you like. When you're ready, talk me through your approach or go straight to the code.

You need to log in / sign up to run or submit.

Problem

CoStar Market Analytics stores product price periods and completed unit sales separately. Write a PostgreSQL query that calculates the average selling price for every product in the pricing table.

A sale matches a price when its purchase_date falls inclusively between start_date and end_date. The average must be weighted by units sold, not calculated as a simple average of listed prices.

Requirements

  1. Return every product_id from prices, including products with no matching sales.
  2. Calculate SUM(price * units) / SUM(units) for each product, rounded to two decimal places.
  3. Return 0.00 when a product has no valid units sold, and order results by product_id ascending.
  4. Do not count sales outside a product's active price period or sales for products absent from prices.

Schema

prices
ColumnTypeDescription
product_idINTProduct identifier; multiple rows represent different price periods.
start_dateDATEInclusive beginning of the price period.
end_dateDATEInclusive end of the price period.
priceNUMERIC(10,2)Listed selling price during the period.
units_sold
ColumnTypeDescription
sale_idPKINTUnique sale identifier.
product_idINTProduct included in the sale.
purchase_dateDATEDate on which the product was purchased.
unitsINTNumber of units purchased.
Tablespricesunits_sold
Your solutionPostgreSQL
You need to log in / sign up to run or submit.
Run a query to see results