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

前端 未结 7 851
我在风中等你
我在风中等你 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 15:58

    Simple sql with native postgres functions only:

    select 
        case count(*)%2
            when 1 then (array_agg(num order by num))[count(*)/2+1]
            else ((array_agg(num order by num))[count(*)/2]::double precision + (array_agg(num order by num))[count(*)/2+1])/2
        end as median
    from unnest(array[5,17,83,27,28]) num;
    

    Sure you can add coalesce() or something if you want to handle nulls.

提交回复
热议问题