Understanding window functions
A window function operates over a set of rows called a window and returns a column that is included with the other selected columns. The window becomes a partition on the table and allows the rows to retain their details while providing an aggregate. That is what makes the window function different from aggregates, even though, in some cases, it is evaluating an aggregate.
Here is a partial list of the window functions:
- Ranking:
ROW_NUMBER
RANK
DENSE_RANK
NTILE
PERCENT_RANK
CUME_DISTLEAD
FIRST_VALUE
LAST_VALUE
COUNT
PERCENTILE_CONT
PERCENTILE_DIST
- Value:
LAG
- Aggregate:
AVG
SUM
MAX/MIN
Next, we will look at the structure of the window functions and the required clauses to create them.
Using a window function in a query
To use a window function in a query, you just include it as a column in the query definition. Every window function requires an OVER
clause and optionally can include a PARTITION BY
clause and an ORDER BY
clause, which is...