首页/数据/SQL 速查/中位数与百分位(percentile_cont)
聚合与窗口函数54 条

中位数与百分位(percentile_cont)

中位数/百分位用分位函数计算:PostgreSQL 用 percentile_cont/percentile_disc;MySQL 8 没有内置等价函数,需要用窗口函数近似或应用层计算。

SQL 速查数据更新于 2026-10-12

PostgreSQL

PostgreSQL
SELECT percentile_cont(0.5) WITHIN GROUP (ORDER BY amount) AS median,
       percentile_cont(0.95) WITHIN GROUP (ORDER BY amount) AS p95,
       percentile_disc(0.5)  WITHIN GROUP (ORDER BY amount) AS median_disc
FROM orders;

MySQL 近似思路

MySQL 近似思路
SELECT AVG(amount) AS approx_median
FROM (
    SELECT amount,
           ROW_NUMBER() OVER (ORDER BY amount) AS rn,
           COUNT(*)   OVER ()                  AS n
    FROM orders
) t
WHERE t.rn IN (FLOOR((t.n + 1) / 2), CEIL((t.n + 1) / 2));
percentile_cont按插值返回连续分位值
percentile_disc返回实际存在于数据中的值
MySQL无内置分位聚合,用窗口函数或应用层

易错点

  • 中位数与平均数的口径不同,监控告警(长尾延迟)用分位数更合适
  • MySQL 近似写法在大表上需要排序整列,评估内存与临时表开销

数据来源与参考

  • PostgreSQL Documentation · Ordered-Set Aggregate Functions
  • MySQL 8.0 Reference Manual · Window Functions
​‌‌​​‌​​​‌‌​‌‌‌‌​‌‌​​​‌‌​‌‌‌​​‌‌​​‌​‌‌‌​​‌‌‌​​​‌​‌‌​‌​​‌​‌‌‌​​​‌​‌‌​‌​​‌​‌‌​​​‌‌​‌‌‌​‌​​​‌‌​‌‌‌‌​​‌​‌‌‌​​‌‌​​​‌‌​‌‌​‌‌‌‌​‌‌​‌‌​‌