在 postgresql 中具有分组的嵌套聚合函数

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11107666/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-21 00:01:18  来源:igfitidea点击:

Nested aggregate functions with grouping in postgresql

sqlpostgresqlgroupingaggregate

提问by ferson2020

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.

也就是说,对于返回的每一行,我希望其中一个字段是总和的平均值,其中每个总和都在 y 相同的行上。

I would like to avoid subselects if possible.

如果可能,我想避免子选择。

回答by Gordon Linoff

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