Search notes:

SQL: Analytic functions

An analytic function computes a value for each returned record by applying the function on a group of records.
This is different from an aggregate function in that the aggregate returns one value per group and that the aggregate function is tied to a group by (The group by can be omitted if the group is the entire selected result).
In the SQL order of operations, aggregate functions are evaluated after the having clause and thus also after the group by clause.

Types of analytic functions

Analytic functions can roughly be divided into the following types
Ranking Calulate the rank, percentile or n-tile of a record in respect to its partition,
Windowing Cumulative and moveing averages (rolling totals). Applies to sum, avg, count, variance and stddev, first_value and last_value.
Reporting
lag / lead Used if one record needs to access values of another record
first / last First or last value of an ordered partition
Linear regeression Slope, intercept etc.
Inversive percentile The value in a partition the belongs to a given percentile
Hypothetical rank and distribution The rank or percentile that a value would have in a given set of values

(Some) analytic functions

Some analytic functions are:

Defining Window into which a row belongs

OVER ( … ROWS  BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING )
OVER ( … ROWS  BETWEEN n         PRECEDING AND m         FOLLOWING )
OVER ( … ROWS  BETWEEN n         PRECEDING AND CURRENT ROW         )
…

OVER ( … RANGE BETWEEN           n        PRECEDING AND           m        FOLLOWING )
OVER ( … RANGE BETWEEN INTERVAL 'n' MONTH PRECEDING AND INTERVAL 'm' MONTH FOLLOWING )
OVER ( … RANGE BETWEEN UNBOUNDED PRECEDING          AND CURRENT ROW                  )
…

Default window

The default window is dependent on if the ORDER BY clause is specified.
With an ORDER BY clause, it is
OVER ( … RANGE BETWEEN UNBOUNDED PRECEDING and CURRENT ROW         )
Without an ORDER BY clause, it is
OVER ( … ROWS  BETWEEN UNBOUNDED PRECEDING and UNBOUNDED FOLLOWING )

QUALIFY clause

Analytic functions are not permitted in where or having clauses, but H2 comes with a qualify clause where they're allowed, see modern SQL.

Navigating within a window

Functions to navigate within a window are
While lag and lead allow to access a specific row relative to the current row, nth_value(n) provides access to to the nth row relative to the first or last row in a window.
first_value and last_value are really just a special case of nth_value(n) where n is 1.

See also

Analytic functions in Oracle.

Index