LEAD() and LAG() Function
The LEAD() and LAG() function in MySQL are used to get preceding and succeeding value of any row within its partition. These functions are termed as nonaggregate Window functions.
The Window functions are those functions which perform operations for each row of the partition or window. These functions produce the result for each query row unlikely to the aggregate functions that group them and results in a single row.
- The row on which operation occur is termed as current row.
- The set of rows which are realted to current row or using which function opaerates on current row is termed as Window.
The LAG() function is used to get value from row that precedes the current row.
The LEAD() function is used to get value from row that succedes the current row.
Syntax:
For LEAD() function-
For LEAD() function-
LEAD(expr, N, default) OVER (Window_specification | Window_name)
For LAG() function-
LAG(expr, N, default) OVER (Window_specification | Window_name)
The N and default argument in the function is optional.
Parameters used:
- expr: It can be a column or any bulit-in function.
- N: It is a positive value which determine number of rows preceding/succeeding the current row. If it is omitted in query then its default value is 1.
- default: It is the default value return by function in-case no row precedes/succeedes the current row by N rows. If it is missing then it is by default NULL.
- OVER(): It defines how rows are partitioned into groups. If OVER() is empty then function compute result using all rows.
- Window_specification: It consist of query partition clause which determines how the query rows are partitioned and ordered.
- Window_name: If window is specified elsewhere in the query then it is referenced using this Window_name.
No comments:
Post a Comment