Skip to content

Instantly share code, notes, and snippets.

@meanother
Created October 14, 2021 19:19
Show Gist options
  • Save meanother/5e391037e357c5434d7369619129f8cf to your computer and use it in GitHub Desktop.
Save meanother/5e391037e357c5434d7369619129f8cf to your computer and use it in GitHub Desktop.
CREATE OR REPLACE FUNCTION _final_median(numeric[])
RETURNS numeric AS
$$
SELECT AVG(val)
FROM (
SELECT val
FROM unnest($1) val
ORDER BY 1
LIMIT 2 - MOD(array_upper($1, 1), 2)
OFFSET CEIL(array_upper($1, 1) / 2.0) - 1
) sub;
$$
LANGUAGE 'sql' IMMUTABLE;
CREATE AGGREGATE median(numeric) (
SFUNC=array_append,
STYPE=numeric[],
FINALFUNC=_final_median,
INITCOND='{}'
);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment