Last active
August 29, 2015 14:23
-
-
Save thoferon/8dafab913a2b36bc09da to your computer and use it in GitHub Desktop.
Aggregate function weighted_avg for PostgreSQL
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 TYPE _weighted_avg_fraction | |
AS (num double precision, denom double precision); | |
CREATE OR REPLACE FUNCTION _weighted_avg_step (acc _weighted_avg_fraction, | |
val anyelement, pond anyelement) RETURNS _weighted_avg_fraction AS $$ | |
BEGIN | |
RETURN (acc.num + val * pond, acc.denom + pond); | |
END; | |
$$ LANGUAGE plpgsql; | |
CREATE OR REPLACE FUNCTION _weighted_avg_final (acc _weighted_avg_fraction) | |
RETURNS double precision AS $$ | |
BEGIN | |
IF acc.denom = 0 | |
THEN RETURN NULL; | |
ELSE RETURN acc.num / acc.denom; | |
END IF; | |
END; | |
$$ LANGUAGE plpgsql; | |
CREATE AGGREGATE weighted_avg (anyelement, anyelement) ( | |
SFUNC = _weighted_avg_step, | |
STYPE = _weighted_avg_fraction, | |
FINALFUNC = _weighted_avg_final, | |
INITCOND = '(0, 0)' | |
); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment