Markus Neumann <markus.neumann@math.uzh.ch> writes:
> if I call
> SELECT myAggrFunction(x) FROM table;
> I get the correct and expected output.
> but when myAggrFunction gets called inside the "wrapper"-function, the
> finalfunction gets executed before all rows are processed and hence I
> get a "Division by zero" error.
> E.g.
> SELECT myWrapperFunction(x) FROM table;
> ERROR: division by zero
> myWrapperFunction would look something like:
> BEGIN
> M := myAggrFunction(x);
> --do some more stuff
> RETURN M;
> END;
That is certainly not going to do what you presumably want.
The outer query doesn't think that the wrapper function is an
aggregate; it's just a plain scalar function that will be called
separately on each row of the table. Meanwhile, the best way
to think about what's happening inside the wrapper is that
M := myAggrFunction(x);
is equivalent to
SELECT myAggrFunction(x) INTO M FROM anonymous-one-row-table;
or if you're an Oracle refugee,
SELECT myAggrFunction(x) INTO M FROM dual;
So the aggregate is evaluated over just one row, and I suppose the
zero-divide error happens because your final function is failing
to cope with that case.
regards, tom lane