PostgreSQL lag,lead获取记录前后的数据

FunctionReturn TypeDescription
lag(value any [, offset integer [, default any ]])same type as valuereturns value evaluated at the row that is offset rows before the current row within the partition; if there is no such row, instead return default. Both offset and default are evaluated with respect to the current row. If omitted, offset defaults to 1 and default to null
lead(value any [, offset integer [, default any ]])same type as valuereturns value evaluated at the row that is offset rows after the current row within the partition; if there is no such row, instead return default. Both offset and default are evaluated with respect to the current row. If omitted, offset defaults to 1 and default to null


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)是一样的。

  • 7
    点赞
  • 11
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值