SQL Window Functions Reference Card 3832
SQL Window Functions Reference Card 3832
Window functions
Window functions allow us to perform certain operations on a subset of related rows, called a window, and return a value for each row in that set.
AGGREGATE
Aggregate window functions are a group of aggregate functions, such as SUM(), COUNT(), AVG(), MAX(), and MIN(), that calculate aggregate values within a window and return a result to
each row.
SELECT
Column_X,
Column_Y, Divides result set into windows based on Column_X.
Column_Z,
AGG_FUNCTION(Column_Z) OVER (
PARTITION BY Column_X
ORDER BY Column_Y) AS Alias
Sorts the rows within each partition by the values in Column_Y.
FROM
Table_name;
RANKING
Ranking window functions assign a rank or row number to each row within a specified window or subset of rows. They work together with the ORDER BY clause.
VALUE-BASED
Value-based window functions are used to extract values from other rows within a window and returns the result for each row within the window.
LAG(Column, n) LEAD(Column, n)
Allows the access of a value within a column from the previous nth-row relative to the Allows the access of a value within a column from the following nth-row relative to the
current row. The lag value for the first row within a partition will be NULL since there is no current row. The lead value for the last row within a partition will be NULL since there is no
previous value. next value.
SELECT SELECT
Column_X, Column_X,
Column_Y, Column_Y,
Column_Z, Column_Z,
LAG(Column_Z, n) OVER LEAD(Column_Z, n) OVER (
PARTITION BY Column_X PARTITION BY Column_X
ORDER BY Column_Y) AS Alias ORDER BY Column_Y) AS Alias
FROM FROM
Table_name; Table_name;
FIRST_VALUE() LAST_VALUE()
Allows the retrieval of the value of a column from the first row within a partition. Allows the retrieval of the value of a column from the last row within a window frame.
SELECT SELECT
Column_X, Column_X,
Column_Y, Column_Y,
Column_Z, Column_Z,
FIRST_VALUE(Column_Z) OVER ( LAST_VALUE(Column_Z) OVER (
PARTITION BY Column_X PARTITION BY Column_X
ORDER BY Column_Y) AS Alias ORDER BY Column_Y) AS Alias
FROM FROM
Table_name; Table_name;