适用于:
Databricks SQL
Databricks Runtime 19 及更高版本
计算时间序列中连续累计计数器值之间的差异,将累计计数器转换为δ格式。
语法
counter_diff( value [, start_time] ) OVER clause
参数
value:表示累积计数器的非负数值表达式。start_time:一个可选TIMESTAMP或TIMESTAMP_NTZ表达式,指示计数器上次重置为零时。 用它来独立于计数器值来表示计数器重置。OVER 子句:描述开窗的子句。
用
PARTITION BY来分开独立的计数器。 典型的分区列包括度量名称和与度量相关的属性。用
ORDER BY来定义顺序。 这通常是与度量相关的时间戳列。
Returns
结果的类型与value匹配。
根据子OVER句中定义ORDER BY的顺序返回当前计数器值与之前计数器值之间的差值。
该函数处理以下情况:
如果
value,NULL则结果为NULL,计算后面行的差分时不使用该行。如果
value是负数,或start_time比前一行start_time更早,Azure Databricks 会报错。对于分区的第一行,结果为
NULL。在计数器重置时,结果为
NULL。如果前一个或电流
start_time为NULL,该值不用于检测计数器重置。
当以下任一条件成立时,Azure Databricks 检测计数器重置:
前
value者大于当前value。start_time提供且大于上一行的start_time。
必须提供 ORDER BY 子句。
常见错误条件
示例
> SELECT m, t, counter_diff(c) OVER (PARTITION BY m ORDER BY t)
FROM VALUES
('http_requests', TIMESTAMP '2026-01-01T00:00:00', 100),
('http_requests', TIMESTAMP '2026-01-01T00:01:00', 200),
('http_requests', TIMESTAMP '2026-01-01T00:02:00', 400)
AS tab(m, t, c);
http_requests 2026-01-01 00:00:00 NULL
http_requests 2026-01-01 00:01:00 100
http_requests 2026-01-01 00:02:00 200
-- Counter reset detected by a decrease in value
> SELECT m, t, counter_diff(c) OVER (PARTITION BY m ORDER BY t)
FROM VALUES
('http_requests', TIMESTAMP '2026-01-01T00:00:00', 100),
('http_requests', TIMESTAMP '2026-01-01T00:01:00', 200),
('http_requests', TIMESTAMP '2026-01-01T00:02:00', 400),
('http_requests', TIMESTAMP '2026-01-01T00:04:00', 50)
AS tab(m, t, c);
http_requests 2026-01-01 00:00:00 NULL
http_requests 2026-01-01 00:01:00 100
http_requests 2026-01-01 00:02:00 200
http_requests 2026-01-01 00:04:00 NULL
-- Counter reset detected by a change in start_time
> SELECT m, t, counter_diff(c, st) OVER (PARTITION BY m ORDER BY t)
FROM VALUES
('http_requests', TIMESTAMP '2026-01-01T00:01:00', TIMESTAMP '2026-01-01T00:00:00', 100),
('http_requests', TIMESTAMP '2026-01-01T00:02:00', TIMESTAMP '2026-01-01T00:00:00', 200),
('http_requests', TIMESTAMP '2026-01-01T00:04:00', TIMESTAMP '2026-01-01T00:02:31', 400)
AS tab(m, t, st, c);
http_requests 2026-01-01 00:01:00 NULL
http_requests 2026-01-01 00:02:00 100
http_requests 2026-01-01 00:04:00 NULL