Interview Questions/SQL/Average Selling Price

Average Selling Price

Preview mode. Log in to edit, run, submit, and save progress.

Medium

Description

You are given two tables - Prices and UnitsSold. The Prices table holds the price of each product within a specific date range. The date ranges for the same product do not overlap. The UnitsSold table logs how many units of each product were sold on a given purchase date. Write a SQL query to find the average selling price for each product. The average selling price is defined as: average_price = SUM(price * units) / SUM(units) Round the result to 2 decimal places. If a product has no sales, report 0 as the average price. Return the result in any order.

Database Schema

Prices

Column NameExample Value
product_id1
start_date2019-02-17
end_date2019-02-28
price5

UnitsSold

Column NameExample Value
product_id1
purchase_date2019-02-25
units100

Example

Prices

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

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

Output

product_idaverage_price
16.96
216.96

Explanation:

Product 1: ((100 * 5) + (15 * 20)) / 115 = 800/115 = 6.96. Product 2: ((200 * 15) + (30 * 30)) / 230 = 3900/230 = 16.96.

Approach hint

Start with a simple approach, explain the trade-off, then move toward a cleaner or more scalable solution.

Common mistake

Skipping assumptions, edge cases, or trade-offs can make an otherwise good answer feel incomplete.

SQL Editor
Loading...

Prices

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

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

Output

product_idaverage_price
16.96
216.96