場景:獲取當前行的下一行某一字段數據,獲取當前行的上一行某一字段數據
1、測試數據:
postgres=# select * from tb1;
id | name
----+------
1 | aa
2 | aa
3 | aa
4 | aa
5 | aa
| bb
| cc
(7 rows)
2. lag(value any [, offset integer [, default any ]]):獲取往前偏移offset的那行的某一字段的數據
參數值 |
說明 |
value any |
指定某一字段 |
offset integer |
向上的偏移量 |
default any |
如果前后的行不存在,則填充的默認值 |
- 獲取上一行的id值,不指定默認值
postgres=# select *,lag(id,1) over(order by id) from tb1;
id | name | lead
----+------+------
1 | aa | --第一行的上一行沒有值,就用null填充
2 | aa | 1
3 | aa | 2
4 | aa | 3
5 | aa | 4
| bb | 5
| cc |
(7 rows)
- 獲取上一行的id值,指定默認值
postgres=# select *,lag(id,1,100) over(order by id) from tb1;
id | name | lag
----+------+-----
1 | aa | 100 --第一行的上一行沒有值,就用指定的默認值100填充
2 | aa | 1
3 | aa | 2
4 | aa | 3
5 | aa | 4
| bb | 5
| cc |
(7 rows)
- 偏移兩行
postgres=# select *,lag(id,2,100) over(order by id) from tb1;
id | name | lag
----+------+-----
1 | aa | 100
2 | aa | 100
3 | aa | 1
4 | aa | 2
5 | aa | 3
| bb | 4
| cc | 5
(7 rows)
-偏移量為-1
postgres=# select *,lag(id,-1,100) over(order by id) from tb1;
id | name | lag
----+------+-----
1 | aa | 2
2 | aa | 3
3 | aa | 4
4 | aa | 5
5 | aa |
| bb |
| cc | 100
(7 rows)
當偏移量為負數的時候,就是取下面行的指定字段的值了。
3. lead(value any [, offset integer [, default any ]]):獲取往后偏移offset的那行的某一字段的數據
- 向下偏移一行
postgres=# select *,lead(id,1,100) over(order by id) from tb1;
id | name | lead
----+------+------
1 | aa | 2
2 | aa | 3
3 | aa | 4
4 | aa | 5
5 | aa |
| bb |
| cc | 100
(7 rows)
可以看到,lag(id, 1) 和 lead(id, -1)是一樣的。