LAG
Description
The LAG function is used to obtain the data of the previous row or a specified number of rows before the current row. By using the LAG function, you can easily access the previous row data within the window for calculations or comparisons.
Syntax
Parameter Description
expr
(any type): The expression for which the previous row is needed.offset
(optional,bigint
type constant, default is 1): Indicates the number of rows to move backward from the current row. When the value is 0, it indicates the current row; when the value is positive, it indicates the number of rows to move backward; when the value is negative, it indicates the number of rows to move forward.default
(optional, constant of the same type asexpr
, default isnull
): The default value used whenoffset
exceeds the window boundary.
Return Result
Returns the same data type as expr
.
Usage Example
- Get the data of the previous row:
Results:
- Get the first two rows of data:
Results:
- Use Default Values:
Results:
Summary
The LAG function is a very useful tool that can help you easily access the previous row of data within a window. By adjusting the offset and default parameters, you can flexibly obtain the required data. In practical applications, the LAG function can be used to calculate moving averages, cumulative sums, and other statistical indicators.