Updated on 2025-05-29 GMT+08:00

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.

  1. The nested aggregate function is located between SELECT and FROM. Otherwise, it is meaningless.
  2. The SELECT statement that uses a nested aggregate function contains a GROUP BY clause.
  3. Only the nested aggregate functions or constant expressions can be selected together with another nested aggregate function.
  4. The aggregate function supports only one nesting operation.
  5. 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.
  6. 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