Percentile Per Group With Cte Join

Ordered-set aggregates cannot be window functions, so compute PERCENTILE_CONT per group in a CTE and join it back to attach the median to every detail row.

SqlData Fetching

Code

snippet
-- ordered-set 聚合(PERCENTILE_CONT / PERCENTILE_DISC ... WITHIN GROUP)
-- 不能当窗口函数使用:"每组中位数"要先用 GROUP BY 算出分位数放进 CTE,
-- 再 join 回明细行,让每一行都带上本组的分位值
CREATE TABLE deliveries (region text NOT NULL, minutes int NOT NULL);
INSERT INTO deliveries VALUES
  ('north', 30), ('north', 42), ('north', 55), ('north', 61),
  ('south', 18), ('south', 26), ('south', 90);

WITH medians AS (
  SELECT
    region,
    PERCENTILE_CONT(0.5) WITHIN GROUP (ORDER BY minutes) AS median_minutes
  FROM deliveries
  GROUP BY region
)
SELECT
  d.region,
  d.minutes,
  m.median_minutes,
  d.minutes - m.median_minutes AS vs_median
FROM deliveries d
JOIN medians m USING (region)
ORDER BY d.region, d.minutes;

How it works

Several statements share this file — SELECT / INSERT / CREATE, with deliveries and medians among the objects 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; NOT NULL qualifiers on the required columns.

Applying it

Run the statement against the deliveries table.

Statements that matter

WITH medians AS (
SELECT
region,
PERCENTILE_CONT(0.5) WITHIN GROUP (ORDER BY minutes) AS median_minutes
FROM deliveries
GROUP BY region
)
SELECT
d.region,
d.minutes,
m.median_minutes,
d.minutes - m.median_minutes AS vs_median
FROM deliveries d
JOIN medians m USING (region)
ORDER BY d.region, d.minutes;
INSERT INTO deliveries VALUES
('north', 30), ('north', 42), ('north', 55), ('north', 61),
('south', 18), ('south', 26), ('south', 90);
CREATE TABLE deliveries (region text NOT NULL, minutes int NOT NULL);

Interactive Tools for This Topic

FAQ

Name the tables involved in this file.
The references are `deliveries`, `medians`, with one join tying the pair together.