# PostgreSQL 教程: avg 函数

## PostgreSQL AVG 函数介绍

`AVG()`函数是 PostgreSQL 中最常用的聚合函数之一。`AVG()`函数允许您计算一组值的平均值。

`AVG()`函数的语法如下：

``````AVG(column)
``````

## PostgreSQL AVG 函数示例

``````SELECT AVG(amount)
FROM payment;
``````
``````        avg
--------------------
4.2006056453822965
(1 row)
``````

``````SELECT AVG(amount)::numeric(10,2)
FROM payment;
``````
`````` avg
------
4.20
(1 row)
``````

### 带 DISTINCT 运算符的 AVG 函数

``````AVG(DISTINCT column)
``````

``````SELECT AVG(DISTINCT amount)::numeric(10,2)
FROM payment;
``````
`````` avg
------
6.14
(1 row)
``````

### 将 AVG 函数与 SUM 函数一起使用

``````SELECT
AVG(amount)::numeric(10,2),
SUM(amount)::numeric(10,2)
FROM
payment;
``````
`````` avg  |   sum
------+----------
4.20 | 61312.04
(1 row)
``````

### 将 AVG 函数与 GROUP BY 子句一起使用

``````SELECT
customer_id,
first_name,
last_name,
AVG (amount)::NUMERIC(10,2)
FROM
payment
INNER JOIN customer USING(customer_id)
GROUP BY
customer_id
ORDER BY
customer_id;
``````

### 将 AVG 函数与 HAVING 子句一起使用

``````SELECT
customer_id,
first_name,
last_name,
AVG (amount)::NUMERIC(10,2)
FROM
payment
INNER JOIN customer USING(customer_id)
GROUP BY
customer_id
HAVING
AVG (amount) > 5
ORDER BY
customer_id;
``````

### AVG 函数和 NULL

``````CREATE TABLE t1 (
id serial PRIMARY KEY,
amount INTEGER
);
``````

``````INSERT INTO t1 (amount)
VALUES
(10),
(NULL),
(30);
``````

`t1`表中的数据如下：

``````SELECT	* FROM 	t1;
``````

``````SELECT AVG(amount)::numeric(10,2)
FROM t1;
``````
``````  avg
-------
20.00
(1 row)
``````

## 了解更多

PostgreSQL 教程：聚合函数

PostgreSQL 文档：聚集函数