cswork / libraryOpen practice workspace

Coding questions · Airbnb

Calculate the Median House Price in Each City

Calculate median house prices by city in PostgreSQL, handling odd and even group sizes, repeated prices, and exact numeric results.

Compute the median house price for each city using PostgreSQL. A city may have an odd or even number of price observations.

Input Table

house_prices

ColumnTypeMeaning
observation_idINTEGERUnique identifier for one observation; primary key
cityTEXTNon-null city name
priceNUMERIC(14,2)Non-null, nonnegative price

The table is the relational representation of city-associated price records for this exercise. Every row is one observation. Repeated prices remain separate observations, even within the same city.

Output Contract

Write one read-only PostgreSQL query returning city and median_price, with one row per city present in house_prices. Sort the output by city ascending. For an odd count, use the middle sorted price. For an even count, use the arithmetic mean of the two middle prices. Return the exact numeric median without rounding to a whole unit.

Example

observation_idcityprice
1Alpha100.00
2Alpha200.00
3Alpha400.00
4Beta200.00
5Beta300.00

Expected result:

citymedian_price
Alpha200.00
Beta250.00

Constraints and Clarifications

  • City names use English letters and are compared as stored; do not merge differently spelled names.
  • A city with one observation has that observation's price as its median.
  • Duplicate prices affect the middle positions; do not apply DISTINCT to prices.
  • There is no separate city catalog, so cities without observations are absent.
  • The median may require three decimal places when the two central prices differ by one cent.

Hint: Identify the central positions

The middle of a city's sorted observations depends on its count. Consider how the same selection of central positions can handle both odd and even counts.

Median House Price by City

Table house_prices

columntypeconstraints
observation_idINTEGERPRIMARY KEY
cityTEXTNOT NULL
priceNUMERIC(14,2)NOT NULL

Sample data:

cityobservation_idprice
Denver1390000
Austin2310000
Boston3610000
Pittsburgh4215000
Austin5450000
Chicago6265000
Boston7575000.5
Austin8310000
Denver9389999.99
Pittsburg1098000
Boston11702000
Austin12525000
Pittsburgh13189500
Boston14575000.49
Austin15298000
Pittsburgh16240250

Expected output

citymedian_price
Austin310000
Boston592500.25
Chicago265000
Denver389999.995
Pittsburg98000
Pittsburgh215000

Hints

  1. The middle of a city's sorted observations depends on its count. Consider how the same selection of central positions can handle both odd and even counts.