Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Nested aggregate functions with grouping in postgresql

I'm trying to get an average of sums using nested aggregate functions and grouping. What I would want to do is:

SELECT AVG(SUM(x) GROUP BY y) WHERE ... GROUP BY ...;

That is, for each row returned, I want one of the fields to be an average of sums, where each sum is over the rows where y is the same.

I would like to avoid subselects if possible.

like image 744
ferson2020 Avatar asked Jun 19 '12 19:06

ferson2020


1 Answers

You need a subquery:

select z, avg(sumval)
from (select y, z, sum(x) as sumval
      from t
      group by y, z
     ) t
group by z
like image 84
Gordon Linoff Avatar answered Oct 29 '22 03:10

Gordon Linoff