3

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?

2 Answers 2

3

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;
Sign up to request clarification or add additional context in comments.

1 Comment

Spot on - I was missing the alias - this would be why I kept getting the syntax error...
2

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

1 Comment

Hmm. Thanks for your help but I'm not sure I fancy reimplementing all the aggregate functions! It just seems a little odd that I can't pass the setof which comes from my original query to the existing ones.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.