Dataford
Interview QuestionsInterview GuidesExperiencesCoaching
New
Pricing
Get started
Dataford
Popular roles
Software EngineerData AnalystData ScientistData EngineerBusiness AnalystAI EngineerMachine Learning EngineerProduct Manager
Browse
Browse All RolesEvery role hub, from analyst to MLBrowse All CompaniesCompany-specific interview loopsAll Interview GuidesThe full guide library
Top questions by role
Software EngineerData AnalystData ScientistData EngineerBusiness AnalystAI EngineerMachine Learning EngineerProduct Manager
Top questions by skill
SQLPythonStatisticsMachine LearningA/B TestingSystem DesignGenerative AIProduct SenseMetricsBehavioral
Browse all questions →Try a mock interview
Experiences
Practice
Mock InterviewsTimed interview simulations with feedbackCoaching1:1 coaching with people at your target companiesSuccess PathYour 6-week structured planModulesCurated lessons by topicWebinarsTalks from ex-Big Tech data leadsPlaygroundA free-form scratch editor
Learn
BlogInterview strategy and career adviceTech Job Market ReportHiring trends across data and AI rolesFor UniversitiesDataford for career centersAbout DatafordWho we are and how we build
Pricing
Build my plan
SQL Average Selling Price
00:00
5 left

SQL Average Selling Price

MediumSQL · PostgreSQL

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
Interviewer

Your question is SQL Average Selling Price. Start with the requirements and the two tables in the Question tab.

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.
CodePostgreSQL
Sign up free to run your codeLog inLn 1
Run your query to see results here.