使用 MySQL where 子句并按 avg() 排序以查找重复单个元素的平均值
mysqlmysqli database更新于 2024/3/15 9:24:00
为此,请使用 having 子句代替 where。让我们首先创建一个表 −
mysql> create table DemoTable1338 -> ( -> Name varchar(10), -> Score int -> ); Query OK, 0 rows affected (1.54 sec)
使用 insert 命令在表中插入一些记录。在这里,我们插入了带有分数的重复姓名 −
mysql> insert into DemoTable1338 values('Chris',8); Query OK, 1 row affected (0.80 sec) mysql> insert into DemoTable1338 values('Bob',4); Query OK, 1 row affected (0.20 sec) mysql> insert into DemoTable1338 values('Bob',9); Query OK, 1 row affected (0.27 sec) mysql> insert into DemoTable1338 values('Chris',6); Query OK, 1 row affected (0.27 sec) mysql> insert into DemoTable1338 values('David',5); Query OK, 1 row affected (0.23 sec) mysql> insert into DemoTable1338 values('David',7); Query OK, 1 row affected (0.40 sec)
使用 select 语句显示表中的所有记录 −
mysql> select * from DemoTable1338;
这将产生以下输出 −
+-------+-------+ | Name | Score | +-------+-------+ | Chris | 8 | | Bob | 4 | | Bob | 9 | | Chris | 6 | | David | 5 | | David | 7 | +-------+-------+ 6 rows in set (0.00 sec)
以下是查找重复单个元素的平均值的查询 −
mysql> select Name,avg(Score) from DemoTable1338 -> group by Name -> having avg(Score) < 9.5 -> order by avg(Score);
这将产生以下输出 −
+-------+------------+ | Name | avg(Score) | +-------+------------+ | David | 6.0000 | | Bob | 6.5000 | | Chris | 7.0000 | +-------+------------+ 3 rows in set (0.00 sec)