Aggregate Functions
Overview
Aggregate functions calculate a group of input values and return a single result. Aggregate functions are usually used together with the GROUP BY clause to aggregate data by group key and calculate the result of each group. They can also be used as window aggregate functions in GROUP WINDOW or OVER WINDOW. All aggregate functions (except COUNT(*)) ignore NULL values by default during calculation. You can use the DISTINCT keyword to remove duplicate values before aggregation.
For more information, see Aggregate Functions.
Application Scenarios
- Collects statistics on metrics by dimension, for example, collecting statistics on the number of orders and average amount by region.
- Performs window aggregate calculation to calculate tumbling or sliding metrics, for example, calculating the UV and GMV in the last 5 minutes.
- Data deduplication statistics, for example, COUNT(DISTINCT user_id) calculates the number of unique visitors.
- Aggregates multi-value fields, for example, collecting labels in a group into a set or concatenating multiple rows of text into one row.
- Identifies the aggregation level in ROLLUP/CUBE multidimensional analysis.
Notes and Constraints
- NULL value processing: Except COUNT(*), all aggregate functions automatically skip NULL values during calculation. If all values in a group are NULL, the aggregation result is NULL.
- DISTINCT restriction: DISTINCT supports only the COUNT, AVG, SUM, and COLLECT functions. MAX, MIN, STDDEV_POP, STDDEV_SAMP, VAR_POP, VAR_SAMP, LISTAGG, GROUPING, BIT_AND, and BIT_OR do not support DISTINCT.
- Nested aggregation: Aggregate functions cannot be nested. For example, SUM(COUNT(*)) is invalid and must be implemented through subqueries.
- GROUP BY consistency: When a non-aggregated column is referenced in the SELECT clause, the column must appear in the GROUP BY clause.
- Windowed aggregation: When an aggregate function is used in an OVER WINDOW clause, it must be used together with ORDER BY and a window frame (ROWS BETWEEN/RANGE BETWEEN).
- Minimum row count for STDDEV_SAMP/VAR_SAMP: The sample standard deviation and sample variance require at least two non-null values in a group. Otherwise, NULL is returned.
- Type constraints for BIT_AND/BIT_OR: Only integer types are supported as input. Passing a non-integer type causes type validation to fail.
- Return type of COLLECT: COLLECT returns the MULTISET type. To convert it to an array, you can use ARRAY_DISTINCT(COLLECT(...)) or other methods.
- Separator of LISTAGG: The separator parameter must be a string constant. Column references or expressions are not supported.
Syntax Structure
| Syntax | Return Type | Description | Example |
|---|---|---|---|
| COUNT(*) | BIGINT | Counts the total number of rows, including rows with NULL values. You do not need to specify columns. This function counts the entire row. | SELECT COUNT(*) FROM orders; -- 10 |
| COUNT(value) | BIGINT | Counts the number of rows in which the value is not NULL. The parameter can be of any type. Rows with NULL values are not counted. | SELECT COUNT(amount) FROM orders; -- 8 (skipping 2 rows with NULL values) |
| COUNT(DISTINCT value) | BIGINT | Counts the number of distinct values after NULL values are removed. The parameter can be of any type. | SELECT COUNT(DISTINCT user_id) FROM orders; -- 5 |
| AVG(value) | DECIMAL / DOUBLE | Calculates the arithmetic average of value. The parameter must be of a numeric type (TINYINT/SMALLINT/INT/BIGINT/FLOAT/DOUBLE/DECIMAL). For integer input, the return type is DECIMAL. For floating-point input, the return type is DOUBLE. NULL values are skipped. | SELECT AVG(price) FROM orders; -- 25.50 |
| AVG(DISTINCT value) | DECIMAL / DOUBLE | Calculates the arithmetic average of value after removing NULL and duplicate values. The parameter must be of a numeric type. The return type rules are the same as those for AVG. | SELECT AVG(DISTINCT price) FROM orders; -- 30.00 |
| SUM(value) | Consistent with the input type | Calculates the sum of value. The parameter must be of a numeric type. For integer input, the return type is integer (INT→INT, BIGINT→BIGINT). For DECIMAL input, the return type is DECIMAL. For FLOAT/DOUBLE input, the return type is DOUBLE. NULL values are skipped. | SELECT SUM(amount) FROM orders; -- 1500 |
| SUM(DISTINCT value) | Consistent with the input type | Calculates the sum of value after removing NULL and duplicate values. The parameter must be of a numeric type. The return type rules are the same as those for SUM. | SELECT SUM(DISTINCT amount) FROM orders; -- 1200 |
| MAX(value) | Consistent with the input type | Returns the maximum value of value. The parameter can be of any comparable type (such as number, string, or date and time). NULL values are skipped. Strings are compared in lexicographic order. | SELECT MAX(price) FROM orders; -- 99.90 |
| MIN(value) | Consistent with the input type | Returns the minimum value of value. The parameter can be of any comparable type (such as number, string, or date and time). NULL values are skipped. Strings are compared in lexicographic order. | SELECT MIN(price) FROM orders; -- 5.00 |
| STDDEV_POP(value) | DOUBLE | Calculates the population standard deviation of value. The parameter must be of the numeric type. The formula is √(Σ(x-μ)²/N). NULL values are skipped. If the number of input rows is less than 1, NULL is returned. | SELECT STDDEV_POP(score) FROM exam; -- 12.45 |
| STDDEV_SAMP(value) | DOUBLE | Calculates the sample standard deviation of value. The parameter must be of the numeric type. The formula is √(Σ(x−μ)²/(N−1)). NULL values are skipped. If the number of input rows is less than 2, NULL is returned. | SELECT STDDEV_SAMP(score) FROM exam; -- 13.20 |
| VAR_POP(value) | DOUBLE | Calculates the population variance of value. The parameter must be of the numeric type. The formula is Σ(x−μ)²/N. NULL values are skipped. If the number of input rows is less than 1, NULL is returned. | SELECT VAR_POP(score) FROM exam; -- 155.00 |
| VAR_SAMP(value) | DOUBLE | Calculates the sample variance of value. The parameter must be of the numeric type. The formula is Σ(x−μ)²/(N−1). NULL values are skipped. If the number of input rows is less than 2, NULL is returned. | SELECT VAR_SAMP(score) FROM exam; -- 174.38 |
| COLLECT(value) | MULTISET | Collects values into a multiset, and retains duplicate elements. The parameter can be of any type. NULL values are skipped. The return type is MULTISET<parameter type>. | SELECT COLLECT(tag) FROM articles; -- [a, b, b, c] |
| COLLECT(DISTINCT value) | MULTISET | Collects values into a multiset after removing NULL values and duplicates. The parameter can be of any type. The return type is MULTISET<parameter type>. | SELECT COLLECT(DISTINCT tag) FROM articles; -- [a, b, c] |
| LISTAGG(value, separator) | STRING | Concatenates value into a single string using separator. The value must be of the string type, and the separator must be a string constant. NULL values are skipped. If there is no separator, pass an empty string '' as the separator. | SELECT LISTAGG(name, ',') FROM users; -- Alice,Bob,Carol |
| GROUPING(expression) | INT | Determines whether the expression is populated with NULL values due to aggregation by GROUP BY ROLLUP or GROUP BY CUBE. A return value of 1 indicates that the column is aggregated (the value is produced by ROLLUP/CUBE), and a return value of 0 indicates that the column retains the original grouping value. This function must be used in a GROUP BY clause that includes ROLLUP or CUBE. | SELECT year, region, GROUPING(region) AS g FROM sales GROUP BY ROLLUP (year, region); -- g=0 (original row) or g=1 (subtotal row) |
| BIT_AND(value) | INT / BIGINT | Performs bitwise AND aggregation on value. The parameter must be of an integer type (TINYINT/SMALLINT/INT/BIGINT). This function is equivalent to performing the & operation on all non-NULL values sequentially. NULL values are skipped. If there is only one non-NULL value, that value itself is returned. | SELECT BIT_AND(flags) FROM events; -- 8 |
| BIT_OR(value) | INT / BIGINT | Performs bitwise OR aggregation on value. The parameter must be of the integer type (TINYINT/SMALLINT/INT/BIGINT). This function is equivalent to performing the OR operation on all non-NULL values in sequence. NULL values are skipped. If there is only one non-NULL value, the value itself is returned. | SELECT BIT_OR(flags) FROM events; -- 15 |
What is your overall rating for this page?
Thank you very much for your feedback. We will continue working to improve the documentation.See the reply and handling status in My Cloud VOC.
For any further questions, feel free to contact us through the chatbot.
Chatbot