Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

multiply(num) aggregate function in postgresql

This could be incredibly simple by the documentation is quite on it. Is there a way to aggregate columns via multiplication operator in postgresql. I know i can do count(column) or sum(column), but is there a multiply(column) or product(column) function that i can use. If not, any ideas how to achieve it.

I'm using postgres 9.1

regards, Hassan

like image 218
saGii Avatar asked Feb 07 '14 08:02

saGii


2 Answers

Sure, just define an aggregate over the base multiplication function. E.g. for bigint:

CREATE AGGREGATE mul(bigint) ( SFUNC = int8mul, STYPE=bigint );

Example:

regress=> SELECT mul(x) FROM generate_series(1,5) x;
 mul 
-----
 120
(1 row)

See CREATE AGGREGATE

like image 129
Craig Ringer Avatar answered Jan 04 '23 04:01

Craig Ringer


Here is a version that works for all numerical data types:

CREATE FUNCTION mul_sfunc(anyelement, anyelement) RETURNS anyelement
   LANGUAGE sql AS 'SELECT $1 * coalesce($2, 1)';

CREATE AGGREGATE mul(anyelement) (
   STYPE = anyelement,
   INITCOND = 1,
   SFUNC = mul_sfunc,
   COMBINEFUNC = mul_sfunc,
   PARALLEL = SAFE
);
like image 31
Laurenz Albe Avatar answered Jan 04 '23 05:01

Laurenz Albe