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

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

    CREATE TABLE array_table (id integer, values integer[]) ;
    
    INSERT INTO array_table VALUES ( 1,'{1,2,3}');
    INSERT INTO array_table VALUES ( 2,'{4,5,6,7}');
    
    select id, values, cardinality(values) as array_length,
    (case when cardinality(values)%2=0 and cardinality(values)>1 then (values[(cardinality(values)/2)]+ values[((cardinality(values)/2)+1)])/2::float 
     else values[(cardinality(values)+1)/2]::float end) as median  
     from array_table
    

    Or you can create a function and use it any where in your further queries.

    CREATE OR REPLACE FUNCTION median (a integer[]) 
    RETURNS float AS    $median$ 
    Declare     
        abc float; 
    BEGIN    
        SELECT (case when cardinality(a)%2=0 and cardinality(a)>1 then 
               (a[(cardinality(a)/2)] + a[((cardinality(a)/2)+1)])/2::float   
               else a[(cardinality(a)+1)/2]::float end) into abc;    
        RETURN abc; 
    END;    
    $median$ 
    LANGUAGE plpgsql;
    
    select id,values,median(values) from array_table
    

提交回复
热议问题