runoops.com

SQL AVG() 函数

AVG() 函数

AVG() 函数返回数值列的平均值。

SQL AVG() 语法

SELECT AVG(column_name) FROM table_name

演示数据库

在本教程中,我们将使用 runoops样本数据库。

下面是 “access_log” 网站访问记录表的数据:

mysql> SELECT * FROM access_log;
+-----+---------+-------+------------+
| aid | site_id | count | date       |
+-----+---------+-------+------------+
|   1 |       1 |    45 | 2020-05-10 |
|   2 |       3 |   100 | 2020-05-13 |
|   3 |       1 |   230 | 2020-05-14 |
|   4 |       2 |    10 | 2020-05-14 |
|   5 |       5 |   205 | 2020-05-14 |
|   6 |       4 |    13 | 2020-05-15 |
|   7 |       3 |   220 | 2020-05-15 |
|   8 |       5 |   545 | 2020-05-16 |
|   9 |       3 |   201 | 2020-05-17 |
+-----+---------+-------+------------+
9 rows in set (0.00 sec)

SQL AVG() 实例

下面的 SQL 语句从 "access_log" 表的 "count" 列获取平均值:

SELECT AVG(count) AS CountAverage FROM access_log;

执行以上 SQL 输出结果如下:

mysql> SELECT AVG(count) AS CountAverage FROM access_log;
+--------------+
| CountAverage |
+--------------+
|     174.3333 |
+--------------+
1 row in set (0.06 sec)

下面的 SQL 语句选择访问量高于平均访问量的 "site_id" 和 "count":

SELECT site_id, count FROM access_log
WHERE count > (SELECT AVG(count) FROM access_log);

执行以上 SQL 输出结果如下:

mysql> SELECT site_id, count FROM access_log
    -> WHERE count > (SELECT AVG(count) FROM access_log);
+---------+-------+
| site_id | count |
+---------+-------+
|       1 |   230 |
|       5 |   205 |
|       3 |   220 |
|       5 |   545 |
|       3 |   201 |
+---------+-------+
5 rows in set (0.00 sec)