Aggregate Function Nesting
Description: Performs another aggregate function operation on the grouping calculation result of the aggregate function.
Generally, it can be described as follows:
SELECT AGG1(AGG2(column_name1)) FROM table_name GROUP BY column_name2;
It is equivalent to:
SELECT AGG1(value) FROM (SELECT AGG2(column_name1) value FROM table_name GROUP BY column_name2);
In the preceding information:
- AGG1(): outer aggregate function.
- AGG2(): inner aggregate function.
- table_name: table name.
- column_name1 and column_name2: column names.
- value: alias of the result of the inner aggregate function.
The overall meaning can be described as follows: The grouping calculation result of the inner aggregate function AGG2() is used as the input of the outer aggregate function AGG1() for recalculation.

- The nested aggregate function is located between SELECT and FROM. Otherwise, it is meaningless.
- The SELECT statement that uses a nested aggregate function contains a GROUP BY clause.
- Only the nested aggregate functions or constant expressions can be selected together with another nested aggregate function.
- The aggregate function supports only one nesting operation.
- Currently, the following aggregate functions can be nested: avg, max, min, sum, var_pop, var_samp, variance, stddev_pop, stddev_samp, stddev, median, regr_sxx, regr_syy, regr_sxy, regr_avgx, regr_avgy, regr_r2, regr_slope, regr_intercept, covar_pop, covar_samp, corr, and listagg.
- The return type of the inner aggregate function must comply with the parameter type of the outer aggregate function.
Example:
gaussdb=# CREATE TABLE test1 (id INT,val INT); CREATE TABLE gaussdb=# INSERT INTO test1 VALUES (1, 1); INSERT 0 1 gaussdb=# INSERT INTO test1 VALUES (1, null); INSERT 0 1 gaussdb=# INSERT INTO test1 VALUES (2, 10); INSERT 0 1 gaussdb=# INSERT INTO test1 VALUES (2, 55); INSERT 0 1 gaussdb=# SELECT SUM(MIN(val)) FROM test1 GROUP BY id; sum ----- 11 (1 row) gaussdb=# DROP TABLE test1; DROP TABLE
Feedback
Was this page helpful?
Provide feedbackThank you very much for your feedback. We will continue working to improve the documentation.