如何获取单个 MySQL 行中的平均值?
你可以为此使用聚合函数 AVG()。我们先创建一个表 -
mysql> create table DemoTable ( Value1 int, Value2 int, Value3 int ); Query OK, 0 rows affected (0.54 sec)
使用 insert 命令向表中插入记录 -
mysql> insert into DemoTable values(10,20,30); Query OK, 1 row affected (0.30 sec) mysql> insert into DemoTable values(13,15,18); Query OK, 1 row affected (0.12 sec) mysql> insert into DemoTable values(21,31,41); Query OK, 1 row affected (0.21 sec)
使用 select 命令显示表中的记录 -
mysql> select *from DemoTable;
这将产生以下输出 -
+--------+--------+--------+ | Value1 | Value2 | Value3 | +--------+--------+--------+ | 10 | 20 | 30 | | 13 | 15 | 18 | | 21 | 31 | 41 | +--------+--------+--------+ 3 rows in set (0.00 sec)
以下是显示单个行中平均值的查询 -
mysql> select avg(Value1+Value2+Value3)/3.0 from DemoTable;
这将产生以下输出 -
+-------------------------------+ | avg(Value1+Value2+Value3)/3.0 | +-------------------------------+ | 22.11111111 | +-------------------------------+ 1 row in set (0.00 sec)
广告