Created
October 7, 2016 17:42
-
-
Save Komzpa/2d3873f88c439d7cbb4de8efa4e058db to your computer and use it in GitHub Desktop.
This file contains 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
create or replace function _final_median(anyarray) | |
returns float8 as $$ | |
with q as | |
( | |
select val | |
from unnest($1) val | |
where VAL is not null | |
order by 1 | |
), | |
cnt as | |
( | |
select COUNT(*) as c | |
from q | |
) | |
select AVG(val) :: float8 | |
from | |
( | |
select val | |
from q | |
limit 2 - MOD((select c | |
from cnt), 2) | |
offset GREATEST(CEIL((select c | |
from cnt) / 2.0) - 1, 0) | |
) q2; | |
$$ language sql immutable parallel safe; | |
drop aggregate if exists median (anyelement); | |
create aggregate median( anyelement ) ( | |
sfunc = array_append, | |
stype = anyarray, | |
finalfunc = _final_median, | |
initcond = '{}', | |
combinefunc = array_cat, | |
parallel = safe | |
); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment