PercentileCont Versus PercentileDisc
Ordered-set aggregates interpolate or select: percentile_cont can return values that never occurred, percentile_disc always returns a real row value.
Code
-- WITHIN GROUP 是有序集聚合:先按组内排序,再按分位取值
-- percentile_cont 在相邻值之间线性插值,结果可能不是表里出现过的值
-- percentile_disc 只从实际出现的值里取分位所在的那个
WITH samples (city, minutes) AS (
VALUES ('a', 10), ('a', 20), ('a', 30),
('b', 15), ('b', 18)
)
SELECT
city,
percentile_cont(0.5) WITHIN GROUP (ORDER BY minutes) AS median_cont,
percentile_disc(0.5) WITHIN GROUP (ORDER BY minutes) AS median_disc
FROM samples
GROUP BY city
ORDER BY city;
-- 组 a:奇数个值 10/20/30 → 两者都返回 20
-- 组 b:偶数个值 15/18 → cont 插值返回 16.5,disc 取偏小一侧返回 15Ordered-set aggregates
Both functions run WITHIN GROUP (ORDER BY minutes): the input is sorted per group first, then the requested fraction is picked. They are aggregates, so GROUP BY city yields one median per city.
Interpolation versus selection
percentile_cont interpolates linearly between neighboring values and can return a number that never appears in the data; percentile_disc always returns an actual row value. Group a (odd count 10/20/30) gives 20 from both; group b (even count 15/18) exposes the split — cont returns 16.5 while disc takes the smaller side and returns 15.
Choosing between them
Reporting that must quote real observed values wants disc; modeling a continuous distribution (SLA math, latency curves) wants cont and must accept interpolated outputs.
Interactive Tools for This Topic
FAQ
- Why can percentile_cont return a value that never occurs?
- It linearly interpolates between adjacent sorted values; the even-sized group b shows it returning 16.5 from inputs 15 and 18.
- Which side does percentile_disc take on even counts?
- The smaller side — the value the 0.5 position falls on in the sorted list, which is 15 for group b.
Report a problem with this exampleOpens a pre-filled issue on GitHub.