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

上一篇 / 下一篇  2016-05-27 17:29:44 / 个人分类:orcale

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

(星星)准备数据

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');

 

 

(星星)lead函数

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');

 

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

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

 

(星星)lag函数

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');

 

 

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

 

(星星)另外

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');

 

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

 

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


TAG:

 

评分:0

我来说两句

日历

« 2024-04-18  
 123456
78910111213
14151617181920
21222324252627
282930    

数据统计

  • 访问量: 65413
  • 日志数: 24
  • 建立时间: 2016-05-27
  • 更新时间: 2016-07-29

RSS订阅

Open Toolbar