Skip to content

Instantly share code, notes, and snippets.

@thoferon
Last active August 29, 2015 14:23
Show Gist options
  • Save thoferon/8dafab913a2b36bc09da to your computer and use it in GitHub Desktop.
Save thoferon/8dafab913a2b36bc09da to your computer and use it in GitHub Desktop.
Aggregate function weighted_avg for PostgreSQL
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