Comparable apartment pairs

Comparable apartment pairs

You are an analyst at the UrbanNest real-estate agency. The appraisal team wants a tool that finds comparable listings: two apartments in the same district with the same number of rooms make a perfect pair for a price sanity check. You have the listings table with active offers. For every district, find all pairs of listings with the same number of rooms. Each pair must appear exactly once: the listing with the smaller id comes first. Listings with an unknown number of rooms (NULL) never form pairs. Return columns: - district — the district; - rooms — number of rooms; - listing_a — id of the listing with the smaller id in the pair; - listing_b — id of the listing with the larger id in the pair; - price_gap — absolute price difference within the pair (raw number, no rounding). Sort by district alphabetically, then listing_a ascending, then listing_b ascending. If a district has three matching listings, all three pairwise combinations must appear.

Expected output sample

This is what a correct answer looks like — its row count is its own, it doesn't have to match the schema tables. Your answer must use the same column names as this sample — alias them with AS if needed.

districtroomslisting_alisting_bprice_gap
Docklands210123000
Hillside37810000
Old Town1455000
PostgreSQLv16

Your query result will appear here

Focus radio
Paused · SomaFM · Fluid