Re: Calculating Median value - Mailing list pgsql-novice

From Tom Lane
Subject Re: Calculating Median value
Date
Msg-id 9087.1525621438@sss.pgh.pa.us
Whole thread Raw
In response to Calculating Median value  (Chandru Aroor <caroor@yahoo.com>)
Responses Re: Calculating Median value
List pgsql-novice
Chandru Aroor <caroor@yahoo.com> writes:
> ... median is defines as follows:
> CREATE AGGREGATE public.median(anyelement) ( SFUNC=array_append, STYPE=anyarray, FINALFUNC=array_median
> I will be honest. I have no clue how that works or what it is supposed
> to do.

It's a user-defined aggregate.  See

https://www.postgresql.org/docs/current/static/xaggr.html

array_append is a built-in function that, in this usage, would just serve
to collect all the input values into an array.  array_median is not the
name of any built-in function, so it must be user-written code.  What
I'd expect it to do, if it's trying to implement the usual definition of
median, is to sort the array and then take the middle element.  Judging
from your description, it's not doing that.

If you're using PG 9.4 or later, you could skip trying to debug this
homegrown version of median and instead use the standard ordered-set
aggregate percentile_cont, or possibly percentile_disc.  See

https://www.postgresql.org/docs/current/static/sql-expressions.html#SYNTAX-AGGREGATES

            regards, tom lane


pgsql-novice by date:

Previous
From: Chandru Aroor
Date:
Subject: Calculating Median value
Next
From: Chandru Aroor
Date:
Subject: Re: Calculating Median value