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.

SqlData Integrity

Code

snippet
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

FAQ

What relations does the SQL touch?
`listings`, `region_median` — joined via one JOIN clause.