LAG
Overview
The LAG()
window function returns the values from specific rows based on the offset argument (previous to the current row in the partition). It can be used with all data types supported by Oxla
Syntax
The syntax for this function is as follows:
The output’s data type for this function is the same as the input’s one. If there is no row that meets the offset criteria, it returns a default value (that must be of a type compatible with the expression value)
Parameters
expression
: column, which will be referencedoffset
: numeric indicator of the previous row to access, that is relative to the current row (optional, if not specified 1 will be returned)default
: value that wil be returned if theoffset
is out of range (optional, if not specifiedNULL
will be returned)
Examples
For the needs of this section, we will create the winsales
table that stores details about some sales transactions:
LAG(expression, offset)
In this example, we will focus on executing the LAG()
function with expression and offset parameters’ values specified:
When executing the query above, it returns the buyer ID, date ID, quantity and previous quantity for all rows with buyer ID equal to c
:
LAG(expression, offset, default)
In this example, we will focus on executing the LAG()
function with expression, offset and default parameters’ values specified:
The query above returns the buyer ID, date ID, quantity and previous buyer ID for all rows: