Window Function LAG
08 Jul 2019This article is an extension of the window function, to follow up on each of the window functions.
The LAG
function returns values in an offset row. The offset is given by the second argument to the function itself. The offset pushes the index above (or before) the selected row.
To demonstrate the effect of this function, we’ll take the sales_id
value, and then we’ll also take a lagged sales_id
. By adjusting the offset value, you’ll see how the lagged value slips down the rows.
Note how the first row here doesn’t have a value, as there isn’t a row above row 1.
sale_id | lag |
---|---|
1 | |
2 | 1 |
3 | 2 |
4 | 3 |
5 | 4 |
Adjusting the index so that it’s now 2
, youll see that both rows 1 and 2 now don’t have a value.
sale_id | lag |
---|---|
1 | |
2 | |
3 | 1 |
4 | 2 |
5 | 3 |