Standard window functions
ClickHouse supports the standard grammar for defining windows and window functions. The table below indicates whether a feature is currently supported.ClickHouse-specific window functions
There is also the following ClickHouse specific window function:nonNegativeDerivative(metric_column, timestamp_column[, INTERVAL X UNITS])
Finds non-negative derivative for givenmetric_column by timestamp_column.
INTERVAL can be omitted, default is INTERVAL 1 SECOND.
The computed value is the following for each row:
0for 1st row,- for row.
Syntax
PARTITION BY- defines how to break a resultset into groups.ORDER BY- defines how to order rows inside the group during calculation aggregate_function.ROWS or RANGE- defines bounds of a frame, aggregate_function is calculated within a frame.WINDOW- allows multiple expressions to use the same window definition.
Functions
These functions can be used only as a window function.row_number()- Number the current row within its partition starting from 1.first_value(x)- Return the first value evaluated within its ordered frame.last_value(x)- Return the last value evaluated within its ordered frame.nth_value(x, offset)- Return the first non-NULL value evaluated against the nth row (offset) in its ordered frame.rank()- Rank the current row within its partition with gaps.dense_rank()- Rank the current row within its partition without gaps.lagInFrame(x)- Return a value evaluated at the row that is at a specified physical offset row before the current row within the ordered frame.leadInFrame(x)- Return a value evaluated at the row that is offset rows after the current row within the ordered frame.
Examples
Let’s have a look at some examples of how window functions can be used.Numbering rows
Aggregation functions
Compare each player’s salary to the average for their team.Partitioning by column
Frame bounding
Real world examples
The following examples solve common real-world problems.Maximum/total salary per department
Cumulative sum
Moving / sliding average (per 3 rows)
Moving / sliding average (per 10 seconds)
Moving / sliding average (per 10 days)
Temperature is stored with second precision, but usingRange and ORDER BY toDate(ts) we form a frame with the size of 10 units, and because of toDate(ts) the unit is a day.