You can use DISTINCT along with COUNT(). Let us first create a table −
mysql> create table DemoTable -> ( -> Id int, -> Score int -> ); Query OK, 0 rows affected (0.95 sec)
Insert some records in the table using insert command −
mysql> insert into DemoTable values(10,90); Query OK, 1 row affected (0.16 sec) mysql> insert into DemoTable values(10,190); Query OK, 1 row affected (0.16 sec) mysql> insert into DemoTable values(11,230); Query OK, 1 row affected (0.18 sec) mysql> insert into DemoTable values(11,130); Query OK, 1 row affected (0.17 sec)
Display all records from the table using select statement −
mysql> select *from DemoTable;
This will produce the following output −
+------+-------+ | Id | Score | +------+-------+ | 10 | 90 | | 10 | 190 | | 11 | 230 | | 11 | 130 | +------+-------+ 4 rows in set (0.00 sec)
Here is the query for averaging a total from a Score column in MySQL with the count of distinct ids. The distinct ids are 2 here, therefore to find the average the total 640 i.e. 90 + 190 + 230 + 130 would be divided with 2 −
mysql> SELECT SUM(Score) / COUNT(DISTINCT Id) from DemoTable;
This will produce the following output −
+---------------------------------+ | SUM(Score) / COUNT(DISTINCT Id) | +---------------------------------+ | 320.0000 | +---------------------------------+ 1 row in set (0.00 sec)