create or replace function wcost_average_sf (numeric[], numeric, numeric) returns numeric[] as $Body$ declare astate numeric[]; begin astate := $1; astate[1] := astate[1] + $2; astate[2] := astate[2] + $2 * $3; return astate; end; $Body$ LANGUAGE 'plpgsql' VOLATILE; create or replace function wcost_average_ff (numeric[] ) returns numeric as $Body$ begin return $1[2]/ $1[1]; end; $Body$ LANGUAGE 'plpgsql' VOLATILE; create aggregate wcost_average (numeric, numeric)( sfunc = wcost_average_sf, stype = numeric[], initcond = '{0,0}', finalfunc = wcost_average_ff );