oracle lag group,Oracle中的lag()和lead()函数的简单用法(统计增长率)

这两个函数,是偏移量函数,其用途是:可以查出同一字段下一个值或上一个值,并作为新列存在表中。

star_yellow.png准备数据

select t.row_id, t.product_code, t.product_price

from cx_infi_price t

where t.row_id in ('59353', '59354', '59355', '59360', '59366', '59359');

image2016-3-7%2011%3A32%3A41.png?version=1&modificationDate=1457321828000&api=v2

star_yellow.pnglead函数

select t.row_id,

t.product_code,

t.product_price,

lead(t.product_price, 1, null) over(order by t.product_price) value

from cx_infi_price t

where t.row_id in ('59353', '59354', '59355', '59360', '59366', '59359');

image2016-3-7%2011%3A34%3A3.png?version=1&modificationDate=1457321828000&api=v2

注:lead函数是按product_price排序,并把当前行product_price的下一个值放到value中,比如:

product_price=15的下一个值是18, product_price=18 的下一个值是59。函数中的null是当没有下一个值时用null代替,当然也可以用其他值替换NULL.

star_yellow.pnglag函数

select t.row_id,

t.product_code,

t.product_price,

lag(t.product_price, 1, null) over(order by t.product_price) value

from cx_infi_price t

where t.row_id in ('59353', '59354', '59355', '59360', '59366', '59359');

image2016-3-7%2011%3A34%3A41.png?version=1&modificationDate=1457321828000&api=v2

lag与lead相反。函数中的1是可以修改的。具体可以运行查看

star_yellow.png另外

select t.row_id,

t.product_code,

t.product_price,

lag(t.product_price) over(order by t.product_price) value

from cx_infi_price t

where t.row_id in ('59353', '59354', '59355', '59360', '59366', '59359');

image2016-3-7%2011%3A35%3A19.png?version=1&modificationDate=1457321828000&api=v2

当然也可以加partition来进行分组,lag的默认参数是1

如果row_id是year_id/month_id,product_price是年收入/月收入,那么就可以用这两个函数来算出月增长率、年增长率了

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值