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

前端 未结 7 823
我在风中等你
我在风中等你 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:07

    Use the Below function for Finding nth percentile

    CREATE or REPLACE FUNCTION nth_percentil(anyarray, int)
        RETURNS 
            anyelement as 
        $$
            SELECT $1[$2/100.0 * array_upper($1,1) + 1] ;
        $$ 
    LANGUAGE SQL IMMUTABLE STRICT;
    

    In Your case it's 50th Percentile.

    Use the Below Query to get the Median

    SELECT nth_percentil(ARRAY (SELECT Field_name FROM table_name ORDER BY 1),50)
    

    This will give you 50th percentile which is the median basically.

    Hope this is helpful.

提交回复
热议问题