COUNT

Counting the number of rows in the table (if * or constant is specified as the argument) or non-empty values in a table column (if the column name is specified as an argument).

Like other aggregate functions, it can be combined with GROUP BY to get statistics on the parts of the table that correspond to the values in the columns being grouped. Use the modifier DISTINCT to count distinct values.

Examples

  1. SELECT COUNT(*) FROM my_table;

Aggregate - 图1

  1. SELECT key, COUNT(value) FROM my_table GROUP BY key;

Aggregate - 图2

  1. SELECT COUNT(DISTINCT value) FROM my_table;

Aggregate - 图3

MIN and MAX

Minimum or maximum value.

As an argument, you may use an arbitrary computable expression with a numeric result.

Examples

  1. SELECT MIN(value), MAX(value) FROM my_table;

Aggregate - 图4

SUM

Sum of the numbers.

As an argument, you may use an arbitrary computable expression with a numeric result.

Integers are automatically expanded to 64 bits to reduce the risk of overflow.

  1. SELECT SUM(value) FROM my_table;

Aggregate - 图5

AVG

Arithmetic average.

As an argument, you may use an arbitrary computable expression with a numeric result.

Integer values and time intervals are automatically converted to Double.

Examples

  1. SELECT AVG(value) FROM my_table;

Aggregate - 图6

COUNT_IF

Number of rows for which the expression specified as the argument is true (the expression’s calculation result is true).

The value NULL is equated to false (if the argument type is Bool?).

The function does not do the implicit type casting to Boolean for strings and numbers.

Examples

  1. SELECT
  2. COUNT_IF(value % 2 == 1) AS odd_count

Aggregate - 图7

Note

To count distinct values in rows meeting the condition, unlike other aggregate functions, you can’t use the modifier DISTINCT because arguments contain no values. To get this result, use in the subquery the built-in function IF with two arguments (to get NULL in else), and apply an outer COUNT(DISTINCT …) to its result.

SUM_IF and AVG_IF

Sum or arithmetic average, but only for the rows that satisfy the condition passed by the second argument.

Therefore, SUM_IF(value, condition) is a slightly shorter notation for SUM(IF(condition, value)), same for AVG. The argument’s data type expansion is similar to the same-name functions without a suffix.

Examples

  1. SELECT
  2. SUM_IF(value, value % 2 == 1) AS odd_sum,
  3. AVG_IF(value, value % 2 == 1) AS odd_avg,
  4. FROM my_table;

Aggregate - 图8

When you use aggregation factories, a Tuple containing a value and a predicate is passed as the first AGGREGATE_BY argument.

Examples

  1. $sum_if_factory = AggregationFactory("SUM_IF");
  2. $avg_if_factory = AggregationFactory("AVG_IF");
  3. SELECT
  4. AGGREGATE_BY(AsTuple(value, value % 2 == 1), $sum_if_factory) AS odd_sum,
  5. AGGREGATE_BY(AsTuple(value, value % 2 == 1), $avg_if_factory) AS odd_avg
  6. FROM my_table;

Aggregate - 图9

SOME

Get the value for an expression specified as an argument, for one of the table rows. Gives no guarantee of which row is used. It’s similar to the any() function in ClickHouse.

Because of no guarantee, SOME is computationally cheaper than MIN/MAX often used in similar situations.

Examples

  1. SELECT
  2. SOME(value)
  3. FROM my_table;

Aggregate - 图10

Alert

When the aggregate function SOME is called multiple times, it’s not guaranteed that all the resulting values are taken from the same row of the source table. To get this guarantee, pack the values into any container and pass it to SOME. For example, in the case of a structure, you can apply AsStruct

CountDistinctEstimate, HyperLogLog, and HLL

Approximating the number of unique values using the HyperLogLog algorithm. Logically, it does the same thing as COUNT(DISTINCT …), but runs much faster at the cost of some error.

Arguments:

  1. Estimated value
  2. Accuracy (4 to 18 inclusive, 14 by default).

By selecting accuracy, you can trade added resource and RAM consumption for decreased error.

All the three functions are aliases at the moment, but CountDistinctEstimate may start using a different algorithm in the future.

Examples

  1. SELECT
  2. CountDistinctEstimate(my_column)
  3. FROM my_table;

Aggregate - 图11

  1. SELECT
  2. HyperLogLog(my_column, 4)
  3. FROM my_table;

Aggregate - 图12

AGGREGATE_LIST

Get all column values as a list. When combined with DISTINCT, it returns only distinct values. The optional second parameter sets the maximum number of values to be returned.

If you know already that you have few distinct values, use the AGGREGATE_LIST_DISTINCT aggregate function to build the same result in memory (that might not be enough for a large number of distinct values).

The order of elements in the result list depends on the implementation and can’t be set externally. To return an ordered list, sort the result, for example, with ListSort.

To return a list of multiple values from one line, DO NOT use the AGGREGATE_LIST function several times, but add all the needed values to a container, for example, via AsList or AsTuple, then pass this container to a single AGGREGATE_LIST call.

For example, you can combine it with DISTINCT and the function String::JoinFromList (it’s an equivalent of ','.join(list) in Python) to output to a string all the values found in the column after GROUP BY.

Examples

  1. SELECT
  2. AGGREGATE_LIST( region ),
  3. AGGREGATE_LIST( region, 5 ),
  4. AGGREGATE_LIST( DISTINCT region ),
  5. AGGREGATE_LIST_DISTINCT( region ),
  6. AGGREGATE_LIST_DISTINCT( region, 5 )
  7. FROM users

Aggregate - 图13

  1. -- An equivalent of GROUP_CONCAT in MySQL
  2. SELECT
  3. String::JoinFromList(CAST(AGGREGATE_LIST(region, 2) AS List<String>), ",")
  4. FROM users

Aggregate - 图14

These functions also have a short notation: AGG_LIST and AGG_LIST_DISTINCT.

Alert

Execution is NOT lazy, so when you use it, be sure that the list has a reasonable size (about a thousand items or less). To stay on the safe side, better use a second optional numeric argument that limits the number of items in the list.

MAX_BY and MIN_BY

Return the value of the first argument for the table row where the second argument is minimum/maximum.

You can optionally specify the third argument N that affects behavior if the table has multiple rows with the same minimum or maximum value:

  • If N is omitted, the value of one of the rows is returned, and the other rows are discarded.
  • If N is specified, the list is returned with all values, but their number can’t exceed N. All values after the number are discarded.

When choosing N, we recommend that you don’t exceed several hundreds or thousands to avoid issues with the limited memory available on YDB clusters.

If your task needs absolutely all values, and their number is measured in dozens of thousands or more, then instead of those aggregate functions better use JOIN on the source table with a subquery doing GROUP BY + MIN/MAX on the desired columns of this table.

Attention

If the second argument is always NULL, the aggregation result is NULL.

When you use aggregation factories, a Tuple containing a value and a key is passed as the first AGGREGATE_BY argument.

Examples

  1. SELECT
  2. MIN_BY(value, LENGTH(value)),
  3. MAX_BY(value, key, 100)
  4. FROM my_table;

Aggregate - 图15

  1. $min_by_factory = AggregationFactory("MIN_BY");
  2. $max_by_factory = AggregationFactory("MAX_BY", 100);
  3. SELECT
  4. AGGREGATE_BY(AsTuple(value, LENGTH(value)), $min_by_factory),
  5. AGGREGATE_BY(AsTuple(value, key), $max_by_factory)
  6. FROM my_table;

Aggregate - 图16

TOP and BOTTOM

Return a list of the maximum/minimum values of an expression. The first argument is an expression, the second argument limits the number of items.

Examples

  1. SELECT
  2. TOP(key, 3),
  3. BOTTOM(value, 3)
  4. FROM my_table;

Aggregate - 图17

  1. $top_factory = AggregationFactory("TOP", 3);
  2. $bottom_factory = AggregationFactory("BOTTOM", 3);
  3. SELECT
  4. AGGREGATE_BY(key, $top_factory),
  5. AGGREGATE_BY(value, $bottom_factory)
  6. FROM my_table;

Aggregate - 图18

TOP_BY and BOTTOM_BY

Return a list of values of the first argument for the rows containing the maximum/minimum values of the second argument. The third argument limits the number of items in the list.

When you use aggregation factories, a Tuple containing a value and a key is passed as the first AGGREGATE_BY argument. In this case, the limit for the number of items is passed by the second argument at factory creation.

Examples

  1. SELECT
  2. TOP_BY(value, LENGTH(value), 3),
  3. BOTTOM_BY(value, key, 3)
  4. FROM my_table;

Aggregate - 图19

  1. $top_by_factory = AggregationFactory("TOP_BY", 3);
  2. $bottom_by_factory = AggregationFactory("BOTTOM_BY", 3);
  3. SELECT
  4. AGGREGATE_BY(AsTuple(value, LENGTH(value)), $top_by_factory),
  5. AGGREGATE_BY(AsTuple(value, key), $bottom_by_factory)
  6. FROM my_table;

Aggregate - 图20

TOPFREQ and MODE

Getting an approximate list of the most common values in a column with an estimation of their count. Returns a list of structures with two fields:

  • Value: the frequently occurring value that was found.
  • Frequency: An estimated value occurrence in the table.

Required argument: the value itself.

Optional arguments:

  1. For TOPFREQ, the desired number of items in the result. MODE is an alias to TOPFREQ with this argument set to 1. For TOPFREQ, this argument is also 1 by default.
  2. The number of items in the buffer used: lets you trade memory consumption for accuracy. Default: 100.

Examples

  1. SELECT
  2. MODE(my_column),
  3. TOPFREQ(my_column, 5, 1000)
  4. FROM my_table;

Aggregate - 图21

STDDEV and VARIANCE

Standard deviation and variance in a column. Those functions use a single-pass parallel algorithm, whose result may differ from the more common methods requiring two passes through the data.

By default, the sample variance and standard deviation are calculated. Several write methods are available:

  • with the POPULATION suffix/prefix, for example: VARIANCE_POPULATION, POPULATION_VARIANCE calculates the variance or standard deviation for the population.
  • With the SAMPLE suffix/prefix or without a suffix, for example, VARIANCE_SAMPLE, SAMPLE_VARIANCE, SAMPLE calculate sample variance and standard deviation.

Several abbreviated aliases are also defined, for example, VARPOP or STDDEVSAMP.

If all the values passed are NULL, it returns NULL.

Examples

  1. SELECT
  2. STDDEV(numeric_column),
  3. VARIANCE(numeric_column)
  4. FROM my_table;

Aggregate - 图22

CORRELATION and COVARIANCE

Correlation and covariance between two columns.

Abbreviated versions are also available: CORR or COVAR. For covariance, there are also versions with the SAMPLE/POPULATION suffix that are similar to VARIANCE above.

Unlike most other aggregate functions, they don’t skip NULL, but accept it as 0.

When you use aggregation factories, a Tuple containing two values is passed as the first AGGREGATE_BY argument.

Examples

  1. SELECT
  2. CORRELATION(numeric_column, another_numeric_column),
  3. COVARIANCE(numeric_column, another_numeric_column)
  4. FROM my_table;

Aggregate - 图23

  1. $corr_factory = AggregationFactory("CORRELATION");
  2. SELECT
  3. AGGREGATE_BY(AsTuple(numeric_column, another_numeric_column), $corr_factory)
  4. FROM my_table;

Aggregate - 图24

PERCENTILE and MEDIAN

Calculating percentiles using the amortized version of the TDigest algorithm. MEDIAN: An alias for PERCENTILE(N, 0.5).

Restriction

The first argument (N) must be a table column name. If you need to bypass this restriction, use a subquery. The restriction is introduced to simplify calculations, since the implementation merges the calls with the same first argument (N) into a single pass.

  1. SELECT
  2. MEDIAN(numeric_column),
  3. PERCENTILE(numeric_column, 0.99)
  4. FROM my_table;

Aggregate - 图25

HISTOGRAM

Plotting an approximate histogram based on a numeric expression with automatic selection of buckets.

Auxiliary functions

Basic settings

You can limit the number of buckets using an optional argument. The default value is 100. Keep in mind that added accuracy costs you more computing resources and may negatively affect the query execution time. In extreme cases, it may affect your query success.

Support for weights

You can specify a “weight” for each value used in the histogram. To do this, pass to the aggregate function the second argument with an expression for calculating the weight. The weight of 1.0 is always used by default. If you use non-standard weights, you may also use the third argument to limit the number of buckets.

If you pass two arguments, the meaning of the second argument is determined by its type (if it’s an integer literal, it limits the number of buckets, otherwise it’s used as a weight).

If you need an accurate histogram

  1. You can use the aggregate functions described below with fixed bucket grids: LinearHistogram or LogarithmicHistogram.
  2. You can calculate the bucket number for each row and apply to it GROUP BY.

When you use aggregation factories, a Tuple containing a value and a weight is passed as the first AGGREGATE_BY argument.

Examples

  1. SELECT
  2. HISTOGRAM(numeric_column)
  3. FROM my_table;

Aggregate - 图26

  1. SELECT
  2. Histogram::Print(
  3. HISTOGRAM(numeric_column, 10),
  4. 50
  5. )
  6. FROM my_table;

Aggregate - 图27

  1. $hist_factory = AggregationFactory("HISTOGRAM");
  2. SELECT
  3. AGGREGATE_BY(AsTuple(numeric_column, 1.0), $hist_factory)
  4. FROM my_table;

Aggregate - 图28

LinearHistogram, LogarithmicHistogram, and LogHistogram

Plotting a histogram based on an explicitly specified fixed bucket scale.

Arguments:

  1. Expression used to plot the histogram. All the following arguments are optional.
  2. Spacing between the LinearHistogram buckets or the logarithm base for LogarithmicHistogram/LogHistogram (those are aliases). In both cases, the default value is 10.
  3. Minimum value. By default, it’s minus infinity.
  4. Maximum value. By default, it’s plus infinity.

The format of the result is totally similar to adaptive histograms, so you can use the same set of auxiliary functions.

If the spread of input values is uncontrollably large, we recommend that you specify the minimum and maximum values to prevent potential failures due to high memory consumption.

Examples

  1. SELECT
  2. LogarithmicHistogram(numeric_column, 2)
  3. FROM my_table;

Aggregate - 图29

BOOL_AND, BOOL_OR and BOOL_XOR

Apply the relevant logical operation (AND/OR/XOR) to all values in a Boolean column or expression.

These functions don’t skip NULL during aggregation, with even one NULL turning the result into NULL. To skip NULLs during aggregation, you can use the functions MIN/MAX or BIT_AND/BIT_OR/BIT_XOR.

Examples

  1. SELECT
  2. BOOL_AND(bool_column),
  3. BOOL_OR(bool_column),
  4. BOOL_XOR(bool_column)
  5. FROM my_table;

Aggregate - 图30

BIT_AND, BIT_OR and BIT_XOR

Apply the relevant bitwise operation to all values of a numeric column or expression.

Examples

  1. SELECT
  2. BIT_XOR(unsigned_numeric_value)
  3. FROM my_table;

Aggregate - 图31

SessionStart

No arguments. It’s allowed only if there is SessionWindow in GROUP BY / PARTITION BY.
Returns the value of the SessionWindow key column. If SessionWindow has two arguments, it returns the minimum value of the first argument within the group/section.
In the case of the expanded version SessionWindow, it returns the value of the second element from the tuple returned by <calculate_lambda>, for which the first tuple element is True.

AGGREGATE_BY and MULTI_AGGREGATE_BY

Applying an aggregation factory to all values of a column or expression. The MULTI_AGGREGATE_BY function requires that the value of a column or expression has a structure, tuple, or list, and applies the factory to each individual element, placing the result in a container of the same format. If different values of a column or expression contain lists of different length, the resulting list will have the smallest of the source lengths.

  1. Column, DISTINCT column or expression.
  2. Factory.

Examples:

  1. $count_factory = AggregationFactory("COUNT");
  2. SELECT
  3. AGGREGATE_BY(DISTINCT column, $count_factory) as uniq_count
  4. FROM my_table;
  5. SELECT
  6. MULTI_AGGREGATE_BY(nums, AggregationFactory("count")) as count,
  7. MULTI_AGGREGATE_BY(nums, AggregationFactory("min")) as min,
  8. MULTI_AGGREGATE_BY(nums, AggregationFactory("max")) as max,
  9. MULTI_AGGREGATE_BY(nums, AggregationFactory("avg")) as avg,
  10. MULTI_AGGREGATE_BY(nums, AggregationFactory("percentile", 0.9)) as p90
  11. FROM my_table;

Aggregate - 图32