Hope this example helps. You need a function that takes (accumulator, aggregated-arguments) and returns a new accumulator value. Play with the code below and this should make you understand how it all fits together.
BEGIN; CREATE FUNCTION sum_product_fn(int,int,int) RETURNS int AS $$ SELECT $1 + ($2 * $3); $$ LANGUAGE SQL; CREATE AGGREGATE sum_product(int, int) ( sfunc = sum_product_fn, stype = int, initcond = 0 ); SELECT sum(i) AS one, sum_product(i, 2) AS double, sum_product(i,3) AS triple FROM generate_series(1,3) i; ROLLBACK;
This should give you something like:
one | double | triple -----+--------+-------- 6 | 12 | 18
source share