[{"createTime":1735734952000,"id":1,"img":"hwy_ms_500_252.jpeg","link":"https://activity.huaweicloud.com/cps.html?fromacct=261f35b6-af54-4511-a2ca-910fa15905d1&utm_source=V1g3MDY4NTY=&utm_medium=cps&utm_campaign=201905","name":"华为云秒杀","status":9,"txt":"华为云38元秒杀","type":1,"updateTime":1735747411000,"userId":3},{"createTime":1736173885000,"id":2,"img":"txy_480_300.png","link":"https://cloud.tencent.com/act/cps/redirect?redirect=1077&cps_key=edb15096bfff75effaaa8c8bb66138bd&from=console","name":"腾讯云秒杀","status":9,"txt":"腾讯云限量秒杀","type":1,"updateTime":1736173885000,"userId":3},{"createTime":1736177492000,"id":3,"img":"aly_251_140.png","link":"https://www.aliyun.com/minisite/goods?userCode=pwp8kmv3","memo":"","name":"阿里云","status":9,"txt":"阿里云2折起","type":1,"updateTime":1736177492000,"userId":3},{"createTime":1735660800000,"id":4,"img":"vultr_560_300.png","link":"https://www.vultr.com/?ref=9603742-8H","name":"Vultr","status":9,"txt":"Vultr送$100","type":1,"updateTime":1735660800000,"userId":3},{"createTime":1735660800000,"id":5,"img":"jdy_663_320.jpg","link":"https://3.cn/2ay1-e5t","name":"京东云","status":9,"txt":"京东云特惠专区","type":1,"updateTime":1735660800000,"userId":3},{"createTime":1735660800000,"id":6,"img":"new_ads.png","link":"https://www.iodraw.com/ads","name":"发布广告","status":9,"txt":"发布广告","type":1,"updateTime":1735660800000,"userId":3},{"createTime":1735660800000,"id":7,"img":"yun_910_50.png","link":"https://activity.huaweicloud.com/discount_area_v5/index.html?fromacct=261f35b6-af54-4511-a2ca-910fa15905d1&utm_source=aXhpYW95YW5nOA===&utm_medium=cps&utm_campaign=201905","name":"底部","status":9,"txt":"高性能云服务器2折起","type":2,"updateTime":1735660800000,"userId":3}]
环境
hive2.x
主要内容
lag函数
应用场景
对某个字段排序,对排序后的结果计算相邻行的差值
模型
diff_age(id string,age int)
("1",10)
("2",30)
("3",100)
中间过程测试
#求相邻id年龄插值
select
id,
age,
lag(age,1,0) over(order by age) as syh
from diff_age
;
-- 结果是全部是Null
select
id,
age,
lag(age,1) over(partition by id order by age) as syh
from diff_age
;
-- 如果上一行没有值,默认值为null
select
id,
age,
lag(age,1) over(order by age) as syh
from diff_age
;
这一段sql和上一段sql的区别是没有加partition by,在网上看到都是加了分区的,这里经过反复测试不加分区才是对的,可能和版本有关系,
有小伙伴在使用这个函数过程中,出现了null问题,可以测试一下
-- 如果上一行没有,则给默认值0
select
id,
age-lag(age,1,0) over(order by age) as nlc
from diff_age
;
lag是可以直接取行数,取不到默认为null,这里给了一个默认值0
lag的用法(字段,向上取几行,取不到给默认值)
这里直接用年龄-取到的值得到年龄差
-- 如果上一行没有,则默认上一行是当前行值
select
id,
age-lag(age,1,age) over(order by age) as nlc
from diff_age
;
这里id=1是没有上一行,默认是就是当前
-- 年龄按顺序排列,求出相邻行年龄差 v1.0
select
*
from(
select
id,
age,
age-lag(age,1,age) over(order by age) as nlc
from diff_age
)tmp
where nlc != 0
;
这里先计算年龄差,默认值是当前,所以第一行减去第一行是0,再通过子查询过滤
这样做会出现bug,如果后续中出现了0,则都会过滤,但只有第一条不符合
-- 年龄按顺序排列,求出相邻行年龄差 v1.1
select
id,
age,
nlc
from(
select
id,
age,
age-lag(age,1,age) over(order by age) as nlc,
row_number() over(order by age) rank
from diff_age
)tmp
where rank != 1
;
这里添加了排序字段,因为排序规则是一样的,所以可以认定是按年龄排序结果与序号是一一对应的
在子查询中过滤序号为1,即第一行