SQL 方言通

首页 / 窗口

LAG 取前第 N 行的值

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

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

各引擎写法

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

迁移注意事项

示例

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

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

同类函数

窗口:全部引擎写法对照

核对日期: · 提交勘误