SQL 方言通

首页 / 窗口

LEAD 取后第 N 行的值

LEAD(expr[, offset[, default]]) 返回当前行后面第 offset 行的值,越界时返回 default。七个引擎写法相同,差异在 default 是否必须是常量、是否支持 IGNORE NULLS,以及 offset 能否为 0。

各引擎写法 · 迁移注意事项 · 示例

各引擎写法

引擎支持写法说明依据
MaxCompute支持LEAD(expr[, offset[, default]]) OVER (...)offset 是大于等于 0 的 BIGINT 常量,0 表示当前行,默认 1。default 是常量,默认 NULL,类型要与 expr 相同。官方文档
Hologres支持LEAD(value[, offset[, default]]) OVER (...)Hologres V1.1.71 起支持。HQE 支持单参数写法。default 默认为空。官方文档
StarRocks支持LEAD(expr [IGNORE NULLS] [, offset[, default]]) OVER (...)offset 必须是正整数,默认 1;default 默认 NULL。IGNORE NULLS 3.0 起支持。4.0 起 default 可以是与 expr 类型兼容的任意表达式。官方文档
Doris支持LEAD(expr[, offset[, default]]) OVER (...)offset 默认 1,返回类型与 expr 相同。官方文档已实测 4.1.5
Hive支持lead(col[, n[, default]]) OVER (...)不指定行数时偏移 1 行。越过窗口末尾时返回 NULL。官方文档已实测 4.2.1
Spark SQL支持lead(input[, offset[, default]]) OVER (...)offset 默认 1,default 默认 NULL。偏移到的行值为 NULL 时返回 NULL,只有该行不存在时才返回 default。官方文档
Flink SQL支持LEAD(expression[, offset][, default])offset 默认 1,default 默认 NULL。官方文档已实测 2.3.0

迁移注意事项

示例

计算与下一笔订单的金额差

MaxCompute
SELECT order_id, amount - LEAD(amount, 1, 0) OVER (PARTITION BY user_id ORDER BY order_time) AS diff FROM orders;
Hologres
SELECT order_id, amount - LEAD(amount, 1, 0) OVER (PARTITION BY user_id ORDER BY order_time) AS diff FROM orders;
StarRocks
SELECT order_id, amount - LEAD(amount, 1, 0) OVER (PARTITION BY user_id ORDER BY order_time) AS diff FROM orders;
Doris
SELECT order_id, amount - LEAD(amount, 1, 0) OVER (PARTITION BY user_id ORDER BY order_time) AS diff FROM orders;
Hive
SELECT order_id, amount - lead(amount, 1, 0) OVER (PARTITION BY user_id ORDER BY order_time) AS diff FROM orders;
Spark SQL
SELECT order_id, amount - lead(amount, 1, 0) OVER (PARTITION BY user_id ORDER BY order_time) AS diff FROM orders;
Flink SQL
SELECT order_id, amount - LEAD(amount, 1, 0) OVER (PARTITION BY user_id ORDER BY order_time) AS diff FROM orders;

同类函数

窗口:全部引擎写法对照

核对日期: · 提交勘误