Question

I have a postgresql table with multiple fields containing integers (a1,a2,a3 etc).

I want to run aggregate functions(mean, standard deviation etc) across more than one of the columns at once. (Some of them may have a reasonable number of nulls, so I don't want to just generate column averages and then average those).

I can get a set of integers with

SELECT unnest(array[a1,a2,a3]) as values FROM table

but I then can't get the aggregate functions to take this as input.

Can anyone give me any hints on how I could get this to work?

Was it helpful?

Solution

With a subquery you have all rows at your disposal:

SELECT sum(val) FROM (
    SELECT unnest(array[a1,a2,a3]) as val FROM table) alias;

You can also group your rows, for example:

SELECT field, sum(val) FROM (
    SELECT field, unnest(array[a1,a2,a3]) as val FROM table) alias
GROUP BY field;

OTHER TIPS

you can define own aggregates for array variable:

CREATE OR REPLACE FUNCTION public.sum_sfunc(double precision, double precision[])
 RETURNS double precision LANGUAGE sql
AS $function$
  SELECT coalesce($1,0) + sum(v) FROM unnest($2) g(v)
$function$

CREATE AGGREGATE sum(BASETYPE=double precision[], 
                      SFUNC=sum_sfunc, STYPE=double precision);

postgres=# select * from fo;
 a  │ b  
────┼────
 10 │ 20
 30 │ 40
(2 rows)

postgres=# select sum(array[a,b]) from fo;
 sum 
─────
 100
(1 row)

Similar steps you can do with other aggregates, but implementation of AVG is little bit harder, and median is next level. But all is possible, see http://www.postgresql.org/docs/9.3/static/xaggr.html

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top