MySQL 查询如何计算一列中的数字平均值?
借助 MySQL 聚合函数 AVG() 计算一列中数字的平均值。
语法如下 −
select avg(yourColumnName) as anyVariableName from yourTableName;
为了理解上述概念,让我们创建一个表。以下是创建表的查询。
mysql> create table AverageCalculateDemo −> ( −> SubjectMarks int −> ); Query OK, 0 rows affected (0.67 sec)
以下是将一些记录插入表的查询 −
mysql> insert into AverageCalculateDemo values(70); Query OK, 1 row affected (0.14 sec) mysql> insert into AverageCalculateDemo values(80); Query OK, 1 row affected (0.19 sec) mysql> insert into AverageCalculateDemo values(65); Query OK, 1 row affected (0.13 sec) mysql> insert into AverageCalculateDemo values(55); Query OK, 1 row affected (0.13 sec) mysql> insert into AverageCalculateDemo values(60); Query OK, 1 row affected (0.23 sec)
使用选择语句显示所有值。以下查询用于显示所有记录 −
mysql> select *from AverageCalculateDemo;
以下是输出 −
+--------------+ | SubjectMarks | +--------------+ | 70 | | 80 | | 65 | | 55 | | 60 | +--------------+ 5 rows in set (0.00 sec)
以下是计算 MySQL 中列平均值的查询 −
mysql> select avg(SubjectMarks) as AverageOf4Numbers from AverageCalculateDemo;
以下是显示平均值的输出 −
+-------------------+ | AverageOf4Numbers | +-------------------+ | 66.0000 | +-------------------+ 1 row in set (0.00 sec)
广告