For this, use having clause instead of where. Let us first create a table −
mysql> create table DemoTable1338 -> ( -> Name varchar(10), -> Score int -> ); Query OK, 0 rows affected (1.54 sec)
Insert some records in the table using insert command. Here, we have inserted duplicate names with scores −
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)
Display all records from the table using select statement −
mysql> select * from DemoTable1338;
This will produce the following output −
+-------+-------+ | Name | Score | +-------+-------+ | Chris | 8 | | Bob | 4 | | Bob | 9 | | Chris | 6 | | David | 5 | | David | 7 | +-------+-------+ 6 rows in set (0.00 sec)
Following is the query to find the average of duplicate individual elements −
mysql> select Name,avg(Score) from DemoTable1338 -> group by Name -> having avg(Score) < 9.5 -> order by avg(Score);
This will produce the following output −
+-------+------------+ | Name | avg(Score) | +-------+------------+ | David | 6.0000 | | Bob | 6.5000 | | Chris | 7.0000 | +-------+------------+ 3 rows in set (0.00 sec)