> ## Documentation Index
> Fetch the complete documentation index at: https://private-7c7dfe99-fix-nav-issues.mintlify.site/llms.txt
> Use this file to discover all available pages before exploring further.

> 用于在指定网格上对时间序列数据计算类似 PromQL 的导数的聚合函数。

# timeSeriesDerivToGrid

<div id="timeSeriesDerivToGrid">
  ## timeSeriesDerivToGrid
</div>

引入版本：v25.6.0

该聚合函数接收由时间戳和值组成的时间序列数据，并在由起始时间戳、结束时间戳和步长定义的规则时间网格上，根据这些数据计算[类似 PromQL 的导数](https://prometheus.io/docs/prometheus/latest/querying/functions/#deriv)。对于网格上的每个点，会在指定的时间窗口内选取样本来计算 `deriv`。

<Note>
  此函数处于 Experimental 阶段，请通过设置 `allow_experimental_ts_to_grid_aggregate_function=true` 启用。
</Note>

**语法**

```sql theme={null}
timeSeriesDerivToGrid(start_timestamp, end_timestamp, grid_step, staleness)(timestamp, value)
```

**参数**

* `start_timestamp` — 指定网格的起始时间。 - `end_timestamp` — 指定网格的结束时间。 - `grid_step` — 指定网格步长，单位为秒。 - `staleness` — 指定所考虑样本允许的最大“滞后”时间，单位为秒。该滞后窗口是左开右闭区间。

**参数**

* `timestamp` — 样本的时间戳。可以是单个值或数组。 - `value` — 与该时间戳对应的时间序列值。可以是单个值或数组。

**返回值**

指定网格上的 `deriv` 值，类型为 `Array(Nullable(Float64))`。返回的数组在时间网格的每个点上都包含一个值。如果窗口内没有足够的样本来计算某个特定网格点的导数值，则该值为 NULL。

**示例**

**计算网格 \[90, 105, 120, 135, 150, 165, 180, 195, 210] 上的导数值**

```sql title=Query theme={null}
WITH
    -- 注意：140 和 190 之间的间隔用于展示如何根据 window 参数为 ts = 150, 165, 180 填充值
    [110, 120, 130, 140, 190, 200, 210, 220, 230]::Array(DateTime) AS timestamps,
    [1, 1, 3, 4, 5, 5, 8, 12, 13]::Array(Float32) AS values, -- 与上述时间戳对应的值数组
    90 AS start_ts,       -- 时间戳网格的起点
    90 + 120 AS end_ts,   -- 时间戳网格的终点
    15 AS step_seconds,   -- 时间戳网格的步长
    45 AS window_seconds  -- "staleness" 窗口
SELECT timeSeriesDerivToGrid(start_ts, end_ts, step_seconds, window_seconds)(timestamp, value)
FROM
(
    -- 此子查询将时间戳数组和值数组转换为 `timestamp`、`value` 行
    SELECT
        arrayJoin(arrayZip(timestamps, values)) AS ts_and_val,
        ts_and_val.1 AS timestamp,
        ts_and_val.2 AS value
);
```

```response title=Response theme={null}
┌─timeSeriesDerivToGrid(start_ts, end_ts, step_seconds, window_seconds)(timestamp, value)─┐
│ [NULL,NULL,0,0.1,0.11,0.15,NULL,NULL,0.15]                                              │
└─────────────────────────────────────────────────────────────────────────────────────────┘
```

**使用数组参数的同一查询**

```sql title=Query theme={null}
WITH
    [110, 120, 130, 140, 190, 200, 210, 220, 230]::Array(DateTime) AS timestamps,
    [1, 1, 3, 4, 5, 5, 8, 12, 13]::Array(Float32) AS values,
    90 AS start_ts,
    90 + 120 AS end_ts,
    15 AS step_seconds,
    45 AS window_seconds
SELECT timeSeriesDerivToGrid(start_ts, end_ts, step_seconds, window_seconds)(timestamps, values);
```

```response title=Response theme={null}
┌─timeSeriesDerivToGrid(start_ts, end_ts, step_seconds, window_seconds)(timestamps, values)─┐
│ [NULL,NULL,0,0.1,0.11,0.15,NULL,NULL,0.15]                                                │
└───────────────────────────────────────────────────────────────────────────────────────────┘
```
