LAG函数
LAG (scalar_expression [,offset] [,default]) OVER ( [ partition_by_clause ] order_by_clause )
GPT 4o国内免费试用,在下方公众号(非本号)后台回复:4o,获取访问方式。
WITH T AS(SELECT 1 ID,10 NUMUNION ALLSELECT 1,20UNION ALLSELECT 1,30UNION ALLSELECT 2,40UNION ALLSELECT 2,50UNION ALLSELECT 2,60)SELECT ID,NUM,LAG(NUM) OVER (PARTITION BY ID ORDER BY NUM) AS OneArgs,LAG(NUM,1) OVER (PARTITION BY ID ORDER BY NUM) AS TowArgs,LAG(NUM,2,0) OVER (PARTITION BY ID ORDER BY NUM) AS ThressArgsFROM T
(提示:可以左右移动代码)
结果如下:
从上面的示例中我们可以看到
1、针对列OneArgs,组内的NUM列的值默认向后偏移了一行,每组的第一行用默认的NULL来代替
2、针对TowArgs,使用了2个参数显示的偏移行,NUM的值也是向后偏移一行。
3、针对ThreeArgs,不仅使用了显示的偏移2行,而且第三个参数将偏移后默认值NULL改成了0
实战例子:如何求解组内上下两行的和?
SELECT ID,NUM,
NUM+LAG(NUM,1,0) OVER (PARTITION BY ID ORDER BY NUM) AS Result
FROM T
结果如下:
注意:第一行因为默认是0,所以每组第一行的结果是NUM+0=NUM
LEAD函数
LEAD函数与LAG函数刚刚相反,它是向前偏移指定的行数,默认是1行。
语法哈参数与LAG类似,这里就不重复介绍了。我们直接看示例:
SELECT ID,NUM,
LEAD(NUM) OVER (PARTITION BY ID ORDER BY NUM) AS OneArgs,
LEAD(NUM,1) OVER (PARTITION BY ID ORDER BY NUM) AS TowArgs,
LEAD(NUM,2,0) OVER (PARTITION BY ID ORDER BY NUM) AS ThressArgs
FROM T
结果:
使用情况与LAG函数类似,只是组内数据分别向前偏移了指定行数。
实战示例:求解同组内上下两行的差?
SELECT ID,NUM,
LEAD(NUM,1,0) OVER (PARTITION BY ID ORDER BY NUM)-NUM AS Result
FROM T
结果:
每组最后一行默认是0,所以0-NUM=-NUM
以上就是这两个函数的相关用法。
原创文章,作者:guozi,如若转载,请注明出处:https://www.sudun.com/ask/89581.html