Is there a better way to calculate the median (not average)

前端 未结 7 833
我在风中等你
我在风中等你 2021-02-02 15:38

Suppose I have the following table definition:

CREATE TABLE x (i serial primary key, value integer not null);

I want to calculate the MEDIAN o

7条回答
  •  余生分开走
    2021-02-02 16:23

    Yes, with PostgreSQL 9.4, you can use the newly introduced inverse distribution function PERCENTILE_CONT(), an ordered-set aggregate function that is specified in the SQL standard as well.

    WITH t(value) AS (
      SELECT 1   UNION ALL
      SELECT 2   UNION ALL
      SELECT 100 
    )
    SELECT
      percentile_cont(0.5) WITHIN GROUP (ORDER BY value)
    FROM
      t;
    

    This emulation of MEDIAN() via PERCENTILE_CONT() is also documented here.

提交回复
热议问题