with tmp as ( select'张三'asname,100as score unionall select'张三'asname,80as score ) select * ,lead(score) over w as lead_score from tmp window w as (partitionbynameorderby score) orderby score
此时结果为
name
score
lead_score
张三
80
100
张三
100
null
有什么作用?
当我们同一个窗口,要取的字段比较多时,窗口的partition by xx order by xxx就会重复编写,此时,如要要修改窗口,那么就会要改很多地方,而使用别名,则只需修改一个地方,同时,代码也会简洁很多。
还是举个例子,比如有如下的订单表
id
用户名
商品
支付时间
购买数量
支付金额
1
张三
奶粉
2023-01-01 13:53:52
2
120
2
张三
尿不湿
2023-01-02 14:14:14
3
200
需求是加上上一次同一个用户购买的商品名称,支付时间,购买金额用于分析比较。
那么,正常的一个sql写法为
1 2 3 4 5 6 7 8 9 10 11
with item_order as ( select1as id,'张三'as name,'奶粉'as item_name,'2023-01-01 13:53:52'as pay_time,2as item_cnt,120as pay_amt unionall select2as id,'张三'as name,'尿不湿'as item_name,'2023-01-02 14:14:14'as pay_time,3as item_cnt,200as pay_amt ) select* ,lag(item_name) over (partitionby name orderby pay_time) as lag_item_name ,lag(pay_time) over (partitionby name orderby pay_time) as lag_pay_time ,lag(pay_amt) over (partitionby name orderby pay_time) as lag_pay_amt from item_order orderby name,pay_time
查看上述sql,会发现写了三次 over (partition by name order by pay_time)
而采用窗口别名复用的方法,sql可以变为如下
1 2 3 4 5 6 7 8 9 10 11 12 13
with item_order as ( select1as id,'张三'as name,'奶粉'as item_name,'2023-01-01 13:53:52'as pay_time,2as item_cnt,120as pay_amt unionall select2as id,'张三'as name,'尿不湿'as item_name,'2023-01-02 14:14:14'as pay_time,3as item_cnt,200as pay_amt ) select* ,lag(item_name) over name_window as lag_item_name ,lag(pay_time) over name_window as lag_pay_time ,lag(pay_amt) over name_window as lag_pay_amt from item_order window name_window as (partitionby name orderby pay_time) orderby name,pay_time