Aggregate functions

更新时间:
复制 MD 格式

AnalyticDB for PostgreSQL supports the aggregate functions of PostgreSQL 12. Aggregate functions perform calculations on a set of input rows and return a single result — for example, computing an average, a sum, or a maximum.

For the full PostgreSQL 12 specification, see Aggregate Functions.

Usage notes

  • All aggregate functions except count() and count(*) return null (not zero) when no input rows exist.

  • array_agg() returns null (not an empty array) when no input rows exist. To replace null with a zero or an empty array, wrap the result with coalesce().

  • For json_object_agg() and jsonb_object_agg(), key names cannot be null, but values can be null.

  • For array_agg() on an array type, all input arrays must have the same dimensionality and cannot be empty or null.

  • Do not use types wrapped by row() as input to array_agg() on non-array types.

General-purpose aggregate functions

FunctionInput typeReturn typeDescription
array_agg()Any non-array typeSame as inputConcatenates input values, including null values, into an array.
array_agg()Any array typeSame as inputConcatenates input arrays into an array of one higher dimension. All inputs must have the same dimensionality and cannot be empty or null.
avg()SMALLINT, INT, BIGINT, REAL, DOUBLE PRECISION, NUMERIC, or INTERVALNUMERIC for integer input; DOUBLE PRECISION for floating-point input; same as input for other typesReturns the average of all non-null input values.
bit_and()SMALLINT, INT, BIGINT, or BITSame as inputReturns the bitwise AND of all non-null input values. Returns null if no non-null values exist.
bit_or()SMALLINT, INT, BIGINT, or BITSame as inputReturns the bitwise OR of all non-null input values. Returns null if no non-null values exist.
bool_and()BOOLBOOLReturns true if all input values are true; otherwise returns false.
bool_or()BOOLBOOLReturns true if at least one input value is true; otherwise returns false.
count(*)BIGINTReturns the total number of input rows, including rows with null values.
count()AnyBIGINTReturns the number of non-null input rows.
every()BOOLBOOLEquivalent to bool_and().
json_agg()AnyJSONAggregates values, including null values, into a JSON array.
jsonb_agg()AnyJSONBAggregates values, including null values, into a JSONB array.
json_object_agg(name, value)(any, any)JSONAggregates key-value pairs into a JSON object. Values can be null; keys cannot.
jsonb_object_agg(name, value)(any, any)JSONBAggregates key-value pairs into a JSONB object. Values can be null; keys cannot.
max()Any array, numeric, string, date/time, network, or enumeration type, or array of these typesSame as inputReturns the maximum non-null value.
min()Any array, numeric, string, date/time, network, or enumeration type, or array of these typesSame as inputReturns the minimum non-null value.
string_agg(expression, delimiter)TEXT or BYTEA (both arguments)Same as inputConcatenates non-null input values into a string, separated by the specified delimiter.
sum()SMALLINT, INT, BIGINT, REAL, DOUBLE PRECISION, NUMERIC, INTERVAL, or MONEYBIGINT for SMALLINT or INT input; NUMERIC for BIGINT input; same as input for other typesReturns the sum of all non-null input values.
xmlagg()XMLXMLConcatenates non-null XML input values.

Examples

The following examples use a sample orders table:

CREATE TABLE orders (
    order_id INT,
    customer_id INT,
    amount DECIMAL(10, 2),
    status TEXT
);

INSERT INTO orders VALUES
    (1, 101, 250.00, 'completed'),
    (2, 101, 80.50,  'completed'),
    (3, 102, NULL,   'pending'),
    (4, 103, 430.00, 'completed'),
    (5, 102, 120.75, 'cancelled');

Count rows and non-null values:

-- Total number of rows
SELECT count(*) FROM orders;
-- Result: 5

-- Number of rows where amount is not null
SELECT count(amount) FROM orders;
-- Result: 4

Compute aggregates on non-null values:

SELECT
    avg(amount)    AS average_amount,   -- ignores the NULL row
    sum(amount)    AS total_amount,
    max(amount)    AS max_amount,
    min(amount)    AS min_amount
FROM orders;
-- average_amount: 220.3125
-- total_amount:   881.25
-- max_amount:     430.00
-- min_amount:     80.50

Group results and collect values into an array:

SELECT
    customer_id,
    array_agg(amount ORDER BY amount) AS amounts
FROM orders
WHERE amount IS NOT NULL
GROUP BY customer_id;
-- customer_id 101: {80.50, 250.00}
-- customer_id 103: {430.00}

Concatenate values into a string:

SELECT string_agg(status, ', ' ORDER BY order_id) AS statuses
FROM orders;
-- Result: 'completed, completed, pending, completed, cancelled'

Statistics-related aggregate functions

All functions in this section accept DOUBLE PRECISION input and return DOUBLE PRECISION (or BIGINT for regr_count).

FunctionReturn typeDescription
corr(Y, X)DOUBLE PRECISIONReturns the correlation coefficient between Y and X.
covar_pop(Y, X)DOUBLE PRECISIONReturns the population covariance between Y and X.
covar_samp(Y, X)DOUBLE PRECISIONReturns the sample covariance between Y and X.
regr_avgx(Y, X)DOUBLE PRECISIONReturns the average of the independent variable X: sum(X)/N, where N is the count of non-null X values.
regr_avgy(Y, X)DOUBLE PRECISIONReturns the average of the dependent variable Y: sum(Y)/N, where N is the count of non-null Y values.
regr_count(Y, X)BIGINTReturns the number of rows where both Y and X are non-null.
regr_intercept(Y, X)DOUBLE PRECISIONReturns the y-intercept of the least-squares linear equation fitted from the (X, Y) data points.
regr_r2(Y, X)DOUBLE PRECISIONReturns the square of the correlation coefficient.
regr_slope(Y, X)DOUBLE PRECISIONReturns the slope of the least-squares linear equation fitted from the (X, Y) data points.
regr_sxx(Y, X)DOUBLE PRECISIONReturns the sum of squares of X: sum(X^2) - sum(X)^2/N.
regr_sxy(Y, X)DOUBLE PRECISIONReturns the sum of products of X and Y: sum(X*Y) - sum(X)*sum(Y)/N, where N is the count of non-null (Y, X) pairs.
regr_syy(Y, X)DOUBLE PRECISIONReturns the sum of squares of Y: sum(Y^2) - sum(Y)^2/N.
stddev()DOUBLE PRECISION for floating-point input; NUMERIC for other typesAlias of stddev_samp().
stddev_pop()DOUBLE PRECISION for floating-point input; NUMERIC for other typesReturns the population standard deviation of the input values.
stddev_samp()DOUBLE PRECISION for floating-point input; NUMERIC for other typesReturns the sample standard deviation of the input values.
variance()DOUBLE PRECISION for floating-point input; NUMERIC for other typesAlias of var_samp().
var_pop()DOUBLE PRECISION for floating-point input; NUMERIC for other typesReturns the population variance of the input values (the square of the population standard deviation).
var_samp()DOUBLE PRECISION for floating-point input; NUMERIC for other typesReturns the sample variance of the input values (the square of the sample standard deviation).

Examples

The following examples use a sample measurements table with sensor readings:

CREATE TABLE measurements (
    sensor_id INT,
    reading DOUBLE PRECISION
);

INSERT INTO measurements VALUES
    (1, 10.5),
    (1, 12.3),
    (1, NULL),
    (2, 8.7),
    (2, 9.1),
    (2, 11.4);

Compute standard deviation and variance per sensor:

SELECT
    sensor_id,
    stddev_samp(reading)  AS sample_stddev,
    stddev_pop(reading)   AS pop_stddev,
    var_samp(reading)     AS sample_variance,
    var_pop(reading)      AS pop_variance
FROM measurements
GROUP BY sensor_id;

Fit a simple linear regression between two columns:

SELECT
    corr(reading, sensor_id)           AS correlation,
    regr_slope(reading, sensor_id)     AS slope,
    regr_intercept(reading, sensor_id) AS intercept,
    regr_r2(reading, sensor_id)        AS r_squared
FROM measurements;