Declaration
LAG { ( value_expr [, offset [, default]]) [ { RESPECT | IGNORE } NULLS ] | ( value_expr [ { RESPECT | IGNORE } NULLS ] [, offset [, default]] )} OVER ([ query_partition_clause ] order_by_clause)
Description
To retrieve the data from the offset rows following the same field in the current row within a single query, you can use a self-join on the same table. However, the LAG() window function is more efficient for this purpose.
Parameters
The meanings of the parameters are described in the following table.
Parameter |
Meaning |
|---|---|
value_expr |
The field to be compared. |
offset |
means value_expr Offset of |
default |
Represents the default return value. Default value: NULL, indicating that the return value is NULL if the default value is not explicitly set. |
[ { RESPECT \| IGNORE } NULLS ] |
Whether to consider NULL Value. Default value: RESPECT NULLS, indicating consideration. NULL Value. |
order_by_clause |
It indicates that data must be sorted on a column before the concept of "first few rows" and "last few rows" can be applied. |
query_partition_clause |
Specifies the partition for the query. If omitted, global data is used by default. |
Examples
obclient> CREATE TABLE EXPLOYEES(LAST_NAME CHAR(10), SALARY DECIMAL, JOB_ID CHAR(32));
Query OK, 0 rows affected
obclient> INSERT INTO EXPLOYEES VALUES('JIM', 2000, 'CLEANER');
Query OK, 1 row affected
obclient> INSERT INTO EXPLOYEES VALUES('MIKE', 12000, 'ENGINEERING');
Query OK, 1 row affected
obclient> INSERT INTO EXPLOYEES VALUES('LILY', 13000, 'ENGINEERING');
Query OK, 1 row affected
obclient> INSERT INTO EXPLOYEES VALUES('TOM', 11000, 'ENGINEERING');
Query OK, 1 row affected
obclient> SELECT LAST_NAME, LEAD(SALARY) OVER(ORDER BY SALARY) LEAD, LAG(SALARY) OVER(ORDER BY SALARY) LAG FROM EXPLOYEES;
+-----------+-------+-------+
| LAST_NAME | LEAD | LAG |
+-----------+-------+-------+
| JIM | 11000 | NULL |
| TOM | 12000 | 2000 |
| MIKE | 13000 | 11000 |
| LILY | NULL | 12000 |
+-----------+-------+-------+
4 rows in set