Created
December 2, 2017 15:57
-
-
Save Revolucent/36452a9d407557df8e68f62a5e56bf71 to your computer and use it in GitHub Desktop.
Calculate a median
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
-- https://wiki.postgresql.org/wiki/Aggregate_Median | |
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