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
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)
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 the offset
is out of range (optional, if not specified NULL
will be returned)For the needs of this section, we will create the winsales
table that stores details about some sales transactions:
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
:
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:
In this example, we will use LAG() to compare each day’s sales quantity (qty
) with the previous day’s quantity, ordered by dateid
:
By executing the query above, we will get the following output: