# 6.14. Aggregate Functions

Aggregate functions operate on a set of values to compute a single result.

Except for count(), count_if(), max_by(), min_by() and approx_distinct(), all of these aggregate functions ignore null values and return null for no input rows or when all values are null. For example, sum() returns null rather than zero and avg() does not include null values in the count. The coalesce function can be used to convert null into zero.

Some aggregate functions such as array_agg() produce different results depending on the order of input values. This ordering can be specified by writing an ORDER BY Clause within the aggregate function:

array_agg(x ORDER BY y DESC)
array_agg(x ORDER BY x, y, z)


## General Aggregate Functions

arbitrary(x) → [same as input]

Returns an arbitrary non-null value of x, if one exists.

array_agg(x) → array<[same as input]>

Returns an array created from the input x elements.

avg(x) → double

Returns the average (arithmetic mean) of all input values.

avg(time interval type) → time interval type

Returns the average interval length of all input values.

bool_and(boolean) → boolean

Returns TRUE if every input value is TRUE, otherwise FALSE.

bool_or(boolean) → boolean

Returns TRUE if any input value is TRUE, otherwise FALSE.

checksum(x) → varbinary

Returns an order-insensitive checksum of the given values.

count(*) → bigint

Returns the number of input rows.

count(x) → bigint

Returns the number of non-null input values.

count_if(x) → bigint

Returns the number of TRUE input values. This function is equivalent to count(CASE WHEN x THEN 1 END).

every(boolean) → boolean

This is an alias for bool_and().

geometric_mean(x) → double

Returns the geometric mean of all input values.

max_by(x, y) → [same as x]

Returns the value of x associated with the maximum value of y over all input values.

max_by(x, y, n) → array<[same as x]>

Returns n values of x associated with the n largest of all input values of y in descending order of y.

min_by(x, y) → [same as x]

Returns the value of x associated with the minimum value of y over all input values.

min_by(x, y, n) → array<[same as x]>

Returns n values of x associated with the n smallest of all input values of y in ascending order of y.

max(x) → [same as input]

Returns the maximum value of all input values.

max(x, n) → array<[same as x]>

Returns n largest values of all input values of x.

min(x) → [same as input]

Returns the minimum value of all input values.

min(x, n) → array<[same as x]>

Returns n smallest values of all input values of x.

reduce_agg(inputValue T, initialState S, inputFunction(S, T, S), combineFunction(S, S, S)) → S

Reduces all input values into a single value. inputFunction will be invoked for each input value. In addition to taking the input value, inputFunction takes the current state, initially initialState, and returns the new state. combineFunction will be invoked to combine two states into a new state. The final state is returned:

SELECT id, reduce_agg(value, 0, (a, b) -> a + b, (a, b) -> a + b)
FROM (
VALUES
(1, 2)
(1, 3),
(1, 4),
(2, 20),
(2, 30),
(2, 40)
) AS t(id, value)
GROUP BY id;
-- (1, 9)
-- (2, 90)

SELECT id, reduce_agg(value, 1, (a, b) -> a * b, (a, b) -> a * b)
FROM (
VALUES
(1, 2),
(1, 3),
(1, 4),
(2, 20),
(2, 30),
(2, 40)
) AS t(id, value)
GROUP BY id;
-- (1, 24)
-- (2, 24000)


The state type must be a boolean, integer, floating-point, or date/time/interval.

sum(x) → [same as input]

Returns the sum of all input values.

## Bitwise Aggregate Functions

bitwise_and_agg(x) → bigint

Returns the bitwise AND of all input values in 2’s complement representation.

bitwise_or_agg(x) → bigint

Returns the bitwise OR of all input values in 2’s complement representation.

## Map Aggregate Functions

histogram(x) -> map(K, bigint)

Returns a map containing the count of the number of times each input value occurs.

map_agg(key, value) -> map(K, V)

Returns a map created from the input key / value pairs.

map_union(x(K, V)) -> map(K, V)

Returns the union of all the input maps. If a key is found in multiple input maps, that key’s value in the resulting map comes from an arbitrary input map.

multimap_agg(key, value) -> map(K, array(V))

Returns a multimap created from the input key / value pairs. Each key can be associated with multiple values.

## Approximate Aggregate Functions

approx_distinct(x) → bigint

Returns the approximate number of distinct input values. This function provides an approximation of count(DISTINCT x). Zero is returned if all input values are null.

This function should produce a standard error of 2.3%, which is the standard deviation of the (approximately normal) error distribution over all possible sets. It does not guarantee an upper bound on the error for any specific input set.

approx_distinct(x, e) → bigint

Returns the approximate number of distinct input values. This function provides an approximation of count(DISTINCT x). Zero is returned if all input values are null.

This function should produce a standard error of no more than e, which is the standard deviation of the (approximately normal) error distribution over all possible sets. It does not guarantee an upper bound on the error for any specific input set. The current implementation of this function requires that e be in the range of [0.0040625, 0.26000].

approx_percentile(x, percentage) → [same as x]

Returns the approximate percentile for all input values of x at the given percentage. The value of percentage must be between zero and one and must be constant for all input rows.

approx_percentile(x, percentages) → array<[same as x]>

Returns the approximate percentile for all input values of x at each of the specified percentages. Each element of the percentages array must be between zero and one, and the array must be constant for all input rows.

approx_percentile(x, w, percentage) → [same as x]

Returns the approximate weighed percentile for all input values of x using the per-item weight w at the percentage p. The weight must be an integer value of at least one. It is effectively a replication count for the value x in the percentile set. The value of p must be between zero and one and must be constant for all input rows.

approx_percentile(x, w, percentage, accuracy) → [same as x]

Returns the approximate weighed percentile for all input values of x using the per-item weight w at the percentage p, with a maximum rank error of accuracy. The weight must be an integer value of at least one. It is effectively a replication count for the value x in the percentile set. The value of p must be between zero and one and must be constant for all input rows. accuracy must be a value greater than zero and less than one, and it must be constant for all input rows.

approx_percentile(x, w, percentages) → array<[same as x]>

Returns the approximate weighed percentile for all input values of x using the per-item weight w at each of the given percentages specified in the array. The weight must be an integer value of at least one. It is effectively a replication count for the value x in the percentile set. Each element of the array must be between zero and one, and the array must be constant for all input rows.

approx_set(x) → HyperLogLog
merge(x) → HyperLogLog
merge(qdigest(T)) -> qdigest(T)
qdigest_agg(x) → qdigest<[same as x]>
qdigest_agg(x, w) → qdigest<[same as x]>
qdigest_agg(x, w, accuracy) → qdigest<[same as x]>
numeric_histogram(buckets, value, weight) → map<double, double>

Computes an approximate histogram with up to buckets number of buckets for all values with a per-item weight of weight. The keys of the returned map are roughly the center of the bin, and the entry is the total weight of the bin. The algorithm is based loosely on:

Yael Ben-Haim and Elad Tom-Tov, "A streaming parallel decision tree algorithm",
J. Machine Learning Research 11 (2010), pp. 849--872.


buckets must be a bigint. value and weight must be numeric.

numeric_histogram(buckets, value) → map<double, double>

Computes an approximate histogram with up to buckets number of buckets for all values. This function is equivalent to the variant of numeric_histogram() that takes a weight, with a per-item weight of 1. In this case, the total weight in the returned map is the count of items in the bin.

## Statistical Aggregate Functions

corr(y, x) → double

Returns correlation coefficient of input values.

covar_pop(y, x) → double

Returns the population covariance of input values.

covar_samp(y, x) → double

Returns the sample covariance of input values.

entropy(c) → double

Returns the log-2 entropy of count input-values.

entropy(c) = \sum_i [ c_i / \sum_j [c_j] \log_2(\sum_j [c_j] / c_i) ]


c must be a bigint column of non-negative values.

The function ignores any NULL count. If the sum of non-NULL counts is 0, it returns 0.

kurtosis(x) → double

Returns the excess kurtosis of all input values. Unbiased estimate using the following expression:

kurtosis(x) = n(n+1)/((n-1)(n-2)(n-3))sum[(x_i-mean)^4]/stddev(x)^4-3(n-1)^2/((n-2)(n-3))

classification_miss_rate(buckets, y, x, weight) → array<double>

Computes the miss-rate part of the receiver operator curve with up to buckets number of buckets. Returns an array of miss-rate values. y should be a boolean outcome value; x should be predictions, each between 0 and 1; weight should be non-negative values, indicating the weight of the instance.

To get an ROC map, use this in conjunction with classification_recall():

MAP(classification_recall(200, outcome, prediction), classification_miss_rate(200, outcome, prediction))

classification_precision(buckets, y, x) → array<double>

This function is equivalent to the variant of classification_precision() that takes a weight, with a per-item weight of 1.

classification_precision(buckets, y, x, weight) → array<double>

Computes the precision part of the precision-recall curve with up to buckets number of buckets. Returns an array of precision values. y should be a boolean outcome value; x should be predictions, each between 0 and 1; weight should be non-negative values, indicating the weight of the instance.

To get a map of recall to precision, use this in conjunction with classification_recall():

MAP(classification_recall(200, outcome, prediction), classification_precision(200, outcome, prediction))

classification_precision(buckets, y, x) → array<double>

This function is equivalent to the variant of classification_precision() that takes a weight, with a per-item weight of 1.

classification_recall(buckets, y, x, weight) → array<double>

Computes the recall part of the precision-recall curve or the receiver operator charateristic curve with up to buckets number of buckets. Returns an array of recall values. y should be a boolean outcome value; x should be predictions, each between 0 and 1; weight should be non-negative values, indicating the weight of the instance.

To get a map of recall to precision, use this in conjunction with classification_recall():

MAP(classification_recall(200, outcome, prediction), classification_precision(200, outcome, prediction))

classification_recall(buckets, y, x) → array<double>

This function is equivalent to the variant of classification_recall() that takes a weight, with a per-item weight of 1.

classification_thresholds(buckets, y, x) → array<double>

Computes the thresholds part of the precision-recall curve with up to buckets number of buckets. Returns an array of thresholds. y should be a boolean outcome value; x should be predictions, each between 0 and 1.

To get a map of thresholds to precision, use this in conjunction with classification_precision():

MAP(classification_thresholds(200, outcome, prediction), classification_precision(200, outcome, prediction))


To get a map of thresholds to recall, use this in conjunction with classification_recall():

MAP(classification_thresholds(200, outcome, prediction), classification_recall(200, outcome, prediction))

regr_intercept(y, x) → double

Returns linear regression intercept of input values. y is the dependent value. x is the independent value.

regr_slope(y, x) → double

Returns linear regression slope of input values. y is the dependent value. x is the independent value.

skewness(x) → double

Returns the skewness of all input values.

stddev(x) → double

This is an alias for stddev_samp().

stddev_pop(x) → double

Returns the population standard deviation of all input values.

stddev_samp(x) → double

Returns the sample standard deviation of all input values.

variance(x) → double

This is an alias for var_samp().

var_pop(x) → double

Returns the population variance of all input values.

var_samp`(x) → double

Returns the sample variance of all input values.