2021-02-02 12:00:41 +00:00
|
|
|
---
|
2022-08-26 19:07:59 +00:00
|
|
|
slug: /zh/sql-reference/aggregate-functions/reference/avg
|
2022-04-10 23:08:18 +00:00
|
|
|
sidebar_position: 5
|
2021-02-02 12:00:41 +00:00
|
|
|
---
|
|
|
|
|
|
|
|
# avg {#agg_function-avg}
|
|
|
|
|
|
|
|
计算算术平均值。
|
|
|
|
|
|
|
|
**语法**
|
|
|
|
|
|
|
|
``` sql
|
|
|
|
avg(x)
|
|
|
|
```
|
|
|
|
|
|
|
|
**参数**
|
|
|
|
|
2021-03-23 15:01:28 +00:00
|
|
|
- `x` — 输入值, 必须是 [Integer](../../../sql-reference/data-types/int-uint.md), [Float](../../../sql-reference/data-types/float.md), 或 [Decimal](../../../sql-reference/data-types/decimal.md)。
|
2021-02-02 12:00:41 +00:00
|
|
|
|
|
|
|
**返回值**
|
|
|
|
|
2021-03-23 15:01:28 +00:00
|
|
|
- 算术平均值,总是 [Float64](../../../sql-reference/data-types/float.md) 类型。
|
|
|
|
- 输入参数 `x` 为空时返回 `NaN` 。
|
2021-02-02 12:00:41 +00:00
|
|
|
|
|
|
|
**示例**
|
|
|
|
|
|
|
|
查询:
|
|
|
|
|
|
|
|
``` sql
|
2021-03-23 15:01:28 +00:00
|
|
|
SELECT avg(x) FROM values('x Int8', 0, 1, 2, 3, 4, 5);
|
2021-02-02 12:00:41 +00:00
|
|
|
```
|
|
|
|
|
|
|
|
结果:
|
|
|
|
|
|
|
|
``` text
|
|
|
|
┌─avg(x)─┐
|
|
|
|
│ 2.5 │
|
|
|
|
└────────┘
|
|
|
|
```
|
|
|
|
|
|
|
|
**示例**
|
|
|
|
|
2021-03-23 15:01:28 +00:00
|
|
|
创建一个临时表:
|
|
|
|
|
2021-02-02 12:00:41 +00:00
|
|
|
查询:
|
|
|
|
|
|
|
|
``` sql
|
|
|
|
CREATE table test (t UInt8) ENGINE = Memory;
|
2021-03-23 15:01:28 +00:00
|
|
|
```
|
|
|
|
|
|
|
|
获取算术平均值:
|
|
|
|
|
|
|
|
查询:
|
|
|
|
|
|
|
|
```
|
|
|
|
SELECT avg(t) FROM test;
|
2021-02-02 12:00:41 +00:00
|
|
|
```
|
|
|
|
|
|
|
|
结果:
|
|
|
|
|
|
|
|
``` text
|
|
|
|
┌─avg(x)─┐
|
|
|
|
│ nan │
|
|
|
|
└────────┘
|
|
|
|
```
|