Parametric Aggregate Functions

Some aggregate functions can accept not only argument columns (used for compression), but a set of parameters – constants for initialization. The syntax is two pairs of brackets instead of one. The first is for parameters, and the second is for arguments.

histogram

Calculates an adaptive histogram. It doesn’t guarantee precise results.

  1. histogram(number_of_bins)(values)

The functions uses A Streaming Parallel Decision Tree Algorithm. The borders of histogram bins are adjusted as new data enters a function. In common case, the widths of bins are not equal.

Parameters

number_of_bins — Upper limit for the number of bins in the histogram. The function automatically calculates the number of bins. It tries to reach the specified number of bins, but if it fails, it uses fewer bins.
valuesExpression resulting in input values.

Returned values

  • Array of Tuples of the following format:

    1. ```
    2. [(lower_1, upper_1, height_1), ... (lower_N, upper_N, height_N)]
    3. ```
    4. - `lower` Lower bound of the bin.
    5. - `upper` Upper bound of the bin.
    6. - `height` Calculated height of the bin.

Example

  1. SELECT histogram(5)(number + 1)
  2. FROM (
  3. SELECT *
  4. FROM system.numbers
  5. LIMIT 20
  6. )
  1. ┌─histogram(5)(plus(number, 1))───────────────────────────────────────────┐
  2. [(1,4.5,4),(4.5,8.5,4),(8.5,12.75,4.125),(12.75,17,4.625),(17,20,3.25)]
  3. └─────────────────────────────────────────────────────────────────────────┘

You can visualize a histogram with the bar function, for example:

  1. WITH histogram(5)(rand() % 100) AS hist
  2. SELECT
  3. arrayJoin(hist).3 AS height,
  4. bar(height, 0, 6, 5) AS bar
  5. FROM
  6. (
  7. SELECT *
  8. FROM system.numbers
  9. LIMIT 20
  10. )
  1. ┌─height─┬─bar───┐
  2. 2.125 █▋
  3. 3.25 ██▌
  4. 5.625 ████▏
  5. 5.625 ████▏
  6. 3.375 ██▌
  7. └────────┴───────┘

In this case, you should remember that you don’t know the histogram bin borders.

sequenceMatch(pattern)(timestamp, cond1, cond2, …)

Checks whether the sequence contains an event chain that matches the pattern.

  1. sequenceMatch(pattern)(timestamp, cond1, cond2, ...)

Warning

Events that occur at the same second may lay in the sequence in an undefined order affecting the result.

Parameters

  • pattern — Pattern string. See Pattern syntax.

  • timestamp — Column considered to contain time data. Typical data types are Date and DateTime. You can also use any of the supported UInt data types.

  • cond1, cond2 — Conditions that describe the chain of events. Data type: UInt8. You can pass up to 32 condition arguments. The function takes only the events described in these conditions into account. If the sequence contains data that isn’t described in a condition, the function skips them.

Returned values

  • 1, if the pattern is matched.
  • 0, if the pattern isn’t matched.

Type: UInt8.

Pattern syntax

  • (?N) — Matches the condition argument at position N. Conditions are numbered in the [1, 32] range. For example, (?1) matches the argument passed to the cond1 parameter.

  • .* — Matches any number of events. You don’t need conditional arguments to match this element of the pattern.

  • (?t operator value) — Sets the time in seconds that should separate two events. For example, pattern (?1)(?t>1800)(?2) matches events that occur more than 1800 seconds from each other. An arbitrary number of any events can lay between these events. You can use the >=, >, <, <= operators.

Examples

Consider data in the t table:

  1. ┌─time─┬─number─┐
  2. 1 1
  3. 2 3
  4. 3 2
  5. └──────┴────────┘

Perform the query:

  1. SELECT sequenceMatch('(?1)(?2)')(time, number = 1, number = 2) FROM t
  1. ┌─sequenceMatch('(?1)(?2)')(time, equals(number, 1), equals(number, 2))─┐
  2. 1
  3. └───────────────────────────────────────────────────────────────────────┘

The function found the event chain where number 2 follows number 1. It skipped number 3 between them, because the number is not described as an event. If we want to take this number into account when searching for the event chain given in the example, we should make a condition for it.

  1. SELECT sequenceMatch('(?1)(?2)')(time, number = 1, number = 2, number = 3) FROM t
  1. ┌─sequenceMatch('(?1)(?2)')(time, equals(number, 1), equals(number, 2), equals(number, 3))─┐
  2. 0
  3. └──────────────────────────────────────────────────────────────────────────────────────────┘

In this case, the function couldn’t find the event chain matching the pattern, because the event for number 3 occured between 1 and 2. If in the same case we checked the condition for number 4, the sequence would match the pattern.

  1. SELECT sequenceMatch('(?1)(?2)')(time, number = 1, number = 2, number = 4) FROM t
  1. ┌─sequenceMatch('(?1)(?2)')(time, equals(number, 1), equals(number, 2), equals(number, 4))─┐
  2. 1
  3. └──────────────────────────────────────────────────────────────────────────────────────────┘

See Also

sequenceCount(pattern)(time, cond1, cond2, …)

Counts the number of event chains that matched the pattern. The function searches event chains that don’t overlap. It starts to search for the next chain after the current chain is matched.

Warning

Events that occur at the same second may lay in the sequence in an undefined order affecting the result.

  1. sequenceCount(pattern)(timestamp, cond1, cond2, ...)

Parameters

  • pattern — Pattern string. See Pattern syntax.

  • timestamp — Column considered to contain time data. Typical data types are Date and DateTime. You can also use any of the supported UInt data types.

  • cond1, cond2 — Conditions that describe the chain of events. Data type: UInt8. You can pass up to 32 condition arguments. The function takes only the events described in these conditions into account. If the sequence contains data that isn’t described in a condition, the function skips them.

Returned values

  • Number of non-overlapping event chains that are matched.

Type: UInt64.

Example

Consider data in the t table:

  1. ┌─time─┬─number─┐
  2. 1 1
  3. 2 3
  4. 3 2
  5. 4 1
  6. 5 3
  7. 6 2
  8. └──────┴────────┘

Count how many times the number 2 occurs after the number 1 with any amount of other numbers between them:

  1. SELECT sequenceCount('(?1).*(?2)')(time, number = 1, number = 2) FROM t
  1. ┌─sequenceCount('(?1).*(?2)')(time, equals(number, 1), equals(number, 2))─┐
  2. 2
  3. └─────────────────────────────────────────────────────────────────────────┘

See Also

windowFunnel

Searches for event chains in a sliding time window and calculates the maximum number of events that occurred from the chain.

The function works according to the algorithm:

  • The function searches for data that triggers the first condition in the chain and sets the event counter to 1. This is the moment when the sliding window starts.

  • If events from the chain occur sequentially within the window, the counter is incremented. If the sequence of events is disrupted, the counter isn’t incremented.

  • If the data has multiple event chains at varying points of completion, the function will only output the size of the longest chain.

Syntax

  1. windowFunnel(window, [mode])(timestamp, cond1, cond2, ..., condN)

Parameters

  • window — Length of the sliding window in seconds.
  • mode - It is an optional argument.
    • 'strict' - When the 'strict' is set, the windowFunnel() applies conditions only for the unique values.
  • timestamp — Name of the column containing the timestamp. Data types supported: Date, DateTime and other unsigned integer types (note that even though timestamp supports the UInt64 type, it’s value can’t exceed the Int64 maximum, which is 2^63 - 1).
  • cond — Conditions or data describing the chain of events. UInt8.

Returned value

The maximum number of consecutive triggered conditions from the chain within the sliding time window.
All the chains in the selection are analyzed.

Type: Integer.

Example

Determine if a set period of time is enough for the user to select a phone and purchase it twice in the online store.

Set the following chain of events:

  1. The user logged in to their account on the store (eventID = 1003).
  2. The user searches for a phone (eventID = 1007, product = 'phone').
  3. The user placed an order (eventID = 1009).
  4. The user made the order again (eventID = 1010).

Input table:

  1. ┌─event_date─┬─user_id─┬───────────timestamp─┬─eventID─┬─product─┐
  2. 2019-01-28 1 2019-01-29 10:00:00 1003 phone
  3. └────────────┴─────────┴─────────────────────┴─────────┴─────────┘
  4. ┌─event_date─┬─user_id─┬───────────timestamp─┬─eventID─┬─product─┐
  5. 2019-01-31 1 2019-01-31 09:00:00 1007 phone
  6. └────────────┴─────────┴─────────────────────┴─────────┴─────────┘
  7. ┌─event_date─┬─user_id─┬───────────timestamp─┬─eventID─┬─product─┐
  8. 2019-01-30 1 2019-01-30 08:00:00 1009 phone
  9. └────────────┴─────────┴─────────────────────┴─────────┴─────────┘
  10. ┌─event_date─┬─user_id─┬───────────timestamp─┬─eventID─┬─product─┐
  11. 2019-02-01 1 2019-02-01 08:00:00 1010 phone
  12. └────────────┴─────────┴─────────────────────┴─────────┴─────────┘

Find out how far the user user_id could get through the chain in a period in January-February of 2019.

Query:

  1. SELECT
  2. level,
  3. count() AS c
  4. FROM
  5. (
  6. SELECT
  7. user_id,
  8. windowFunnel(6048000000000000)(timestamp, eventID = 1003, eventID = 1009, eventID = 1007, eventID = 1010) AS level
  9. FROM trend
  10. WHERE (event_date >= '2019-01-01') AND (event_date <= '2019-02-02')
  11. GROUP BY user_id
  12. )
  13. GROUP BY level
  14. ORDER BY level ASC

Result:

  1. ┌─level─┬─c─┐
  2. 4 1
  3. └───────┴───┘

retention

The function takes as arguments a set of conditions from 1 to 32 arguments of type UInt8 that indicate whether a certain condition was met for the event.
Any condition can be specified as an argument (as in WHERE).

The conditions, except the first, apply in pairs: the result of the second will be true if the first and second are true, of the third if the first and third are true, etc.

Syntax

  1. retention(cond1, cond2, ..., cond32);

Parameters

  • cond — an expression that returns a UInt8 result (1 or 0).

Returned value

The array of 1 or 0.

  • 1 — condition was met for the event.
  • 0 — condition wasn’t met for the event.

Type: UInt8.

Example

Let’s consider an example of calculating the retention function to determine site traffic.

1. Сreate a table to illustrate an example.

  1. CREATE TABLE retention_test(date Date, uid Int32) ENGINE = Memory;
  2. INSERT INTO retention_test SELECT '2020-01-01', number FROM numbers(5);
  3. INSERT INTO retention_test SELECT '2020-01-02', number FROM numbers(10);
  4. INSERT INTO retention_test SELECT '2020-01-03', number FROM numbers(15);

Input table:

Query:

  1. SELECT * FROM retention_test

Result:

  1. ┌───────date─┬─uid─┐
  2. 2020-01-01 0
  3. 2020-01-01 1
  4. 2020-01-01 2
  5. 2020-01-01 3
  6. 2020-01-01 4
  7. └────────────┴─────┘
  8. ┌───────date─┬─uid─┐
  9. 2020-01-02 0
  10. 2020-01-02 1
  11. 2020-01-02 2
  12. 2020-01-02 3
  13. 2020-01-02 4
  14. 2020-01-02 5
  15. 2020-01-02 6
  16. 2020-01-02 7
  17. 2020-01-02 8
  18. 2020-01-02 9
  19. └────────────┴─────┘
  20. ┌───────date─┬─uid─┐
  21. 2020-01-03 0
  22. 2020-01-03 1
  23. 2020-01-03 2
  24. 2020-01-03 3
  25. 2020-01-03 4
  26. 2020-01-03 5
  27. 2020-01-03 6
  28. 2020-01-03 7
  29. 2020-01-03 8
  30. 2020-01-03 9
  31. 2020-01-03 10
  32. 2020-01-03 11
  33. 2020-01-03 12
  34. 2020-01-03 13
  35. 2020-01-03 14
  36. └────────────┴─────┘

2. Group users by unique ID uid using the retention function.

Query:

  1. SELECT
  2. uid,
  3. retention(date = '2020-01-01', date = '2020-01-02', date = '2020-01-03') AS r
  4. FROM retention_test
  5. WHERE date IN ('2020-01-01', '2020-01-02', '2020-01-03')
  6. GROUP BY uid
  7. ORDER BY uid ASC

Result:

  1. ┌─uid─┬─r───────┐
  2. 0 [1,1,1]
  3. 1 [1,1,1]
  4. 2 [1,1,1]
  5. 3 [1,1,1]
  6. 4 [1,1,1]
  7. 5 [0,0,0]
  8. 6 [0,0,0]
  9. 7 [0,0,0]
  10. 8 [0,0,0]
  11. 9 [0,0,0]
  12. 10 [0,0,0]
  13. 11 [0,0,0]
  14. 12 [0,0,0]
  15. 13 [0,0,0]
  16. 14 [0,0,0]
  17. └─────┴─────────┘

3. Calculate the total number of site visits per day.

Query:

  1. SELECT
  2. sum(r[1]) AS r1,
  3. sum(r[2]) AS r2,
  4. sum(r[3]) AS r3
  5. FROM
  6. (
  7. SELECT
  8. uid,
  9. retention(date = '2020-01-01', date = '2020-01-02', date = '2020-01-03') AS r
  10. FROM retention_test
  11. WHERE date IN ('2020-01-01', '2020-01-02', '2020-01-03')
  12. GROUP BY uid
  13. )

Result:

  1. ┌─r1─┬─r2─┬─r3─┐
  2. 5 5 5
  3. └────┴────┴────┘

Where:

  • r1- the number of unique visitors who visited the site during 2020-01-01 (the cond1 condition).
  • r2- the number of unique visitors who visited the site during a specific time period between 2020-01-01 and 2020-01-02 (cond1 and cond2 conditions).
  • r3- the number of unique visitors who visited the site during a specific time period between 2020-01-01 and 2020-01-03 (cond1 and cond3 conditions).

uniqUpTo(N)(x)

Calculates the number of different argument values ​​if it is less than or equal to N. If the number of different argument values is greater than N, it returns N + 1.

Recommended for use with small Ns, up to 10. The maximum value of N is 100.

For the state of an aggregate function, it uses the amount of memory equal to 1 + N * the size of one value of bytes.
For strings, it stores a non-cryptographic hash of 8 bytes. That is, the calculation is approximated for strings.

The function also works for several arguments.

It works as fast as possible, except for cases when a large N value is used and the number of unique values is slightly less than N.

Usage example:

  1. Problem: Generate a report that shows only keywords that produced at least 5 unique users.
  2. Solution: Write in the GROUP BY query SearchPhrase HAVING uniqUpTo(4)(UserID) >= 5

Original article

sumMapFiltered(keys_to_keep)(keys, values)

Same behavior as sumMap except that an array of keys is passed as a parameter. This can be especially useful when working with a high cardinality of keys.