PERCENTILE_CONT Median Per Group
Compute each group median with PERCENTILE_CONT WITHIN GROUP, including interpolated even-count values, then join the aggregate back per row.
Code
WITH region_median AS (
SELECT
region,
-- 中位数落在两行之间时按位置插值,这是 median() 的连续定义
percentile_cont(0.5) WITHIN GROUP (ORDER BY price) AS median_price,
percentile_cont(0.25) WITHIN GROUP (ORDER BY price) AS q1_price
FROM listings
GROUP BY region
)
SELECT
l.region,
l.city,
l.price,
m.median_price,
-- 每行对照所在组的中位数,超出 1.5 倍即疑似离群
round(l.price::numeric / NULLIF(m.median_price, 0), 2) AS ratio_to_median
FROM listings l
JOIN region_median m USING (region)
ORDER BY l.region, l.price DESC;How the snippet works
What runs is SELECT, with listings and region_median as the object involved.
Mechanically, the statements are built from: a CTE (WITH … AS) that names an intermediate result before the main query; one JOIN combining rows across tables; a GROUP BY that collapses matching rows into one output row per group; an ORDER BY that fixes the output order.
Applying it
The listings table is the working surface here.
Interactive Tools for This Topic
SQL DDL to TypeScript ConverterConvert SQL CREATE TABLE DDL statements into strict TypeScript interfaces with nullable, array, enum, JSONB, and Date or ISO string column mappings.PostgreSQL EXPLAIN AnalyzerAnalyze PostgreSQL EXPLAIN ANALYZE text or FORMAT JSON plans locally to flag Seq Scans, slow nodes, row misestimates, disk sorts, and index hints.Multi-Mode Escape & Unescape CodecEscape and unescape strings safely across JSON, JavaScript, SQL single-quoted literals, POSIX shell single quotes, and RFC 4180 CSV cells in your browser.SQL FormatterReformat SQL by uppercasing reserved words and breaking lines before SELECT, FROM, WHERE, and other clauses.
FAQ
- What relations does the SQL touch?
- `listings`, `region_median` — joined via one JOIN clause.
Report a problem with this exampleOpens a pre-filled issue on GitHub.