> ## 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.

> 计算 `Σ((x - x̅)(y - y̅)) / (n - 1)`

# covarSamp

<h2 id="covarSamp">
  covarSamp
</h2>

引入版本：v1.1.0

计算样本协方差：

$$
\frac{\Sigma{(x - \bar{x})(y - \bar{y})}}{n - 1}
$$

<Note>
  此函数使用数值不稳定的算法。如果计算中需要[数值稳定性](https://en.wikipedia.org/wiki/Numerical_stability)，请改用 [`covarSampStable`](/reference/functions/aggregate-functions/covarSampStable) 函数。该函数速度较慢，但计算误差更小。
</Note>

**语法**

```sql theme={null}
covarSamp(x, y)
```

**别名**：`COVAR_SAMP`

**参数**

* `x` — 第一个变量。[`(U)Int*`](/reference/data-types/int-uint) 或 [`Float*`](/reference/data-types/float) 或 [`Decimal`](/reference/data-types/decimal)
* `y` — 第二个变量。[`(U)Int*`](/reference/data-types/int-uint) 或 [`Float*`](/reference/data-types/float) 或 [`Decimal`](/reference/data-types/decimal)

**返回值**

返回 `x` 与 `y` 之间的样本协方差。当 `n <= 1` 时，返回 `nan`。[`Float64`](/reference/data-types/float)

**示例**

**基本样本协方差计算**

```sql title=Query theme={null}
DROP TABLE IF EXISTS series;
CREATE TABLE series(i UInt32, x_value Float64, y_value Float64) ENGINE = Memory;
INSERT INTO series(i, x_value, y_value) VALUES (1, 5.6,-4.4),(2, -9.6,3),(3, -1.3,-4),(4, 5.3,9.7),(5, 4.4,0.037),(6, -8.6,-7.8),(7, 5.1,9.3),(8, 7.9,-3.6),(9, -8.2,0.62),(10, -3,7.3);

SELECT covarSamp(x_value, y_value)
FROM series
```

```response title=Response theme={null}
┌─covarSamp(x_value, y_value)─┐
│           7.206275555555556 │
└─────────────────────────────┘
```

**单个值返回 NaN**

```sql title=Query theme={null}
SELECT covarSamp(x_value, y_value)
FROM series LIMIT 1
```

```response title=Response theme={null}
┌─covarSamp(x_value, y_value)─┐
│                         nan │
└─────────────────────────────┘
```
