MySQL query to find the average of rows with the same ID


Let us first create a table −

mysql> create table DemoTable
(
   StudentId int,
   StudentMarks int
);
Query OK, 0 rows affected (0.83 sec)

Insert some records in the table using insert command −

mysql> insert into DemoTable values(1000,78);
Query OK, 1 row affected (0.16 sec)
mysql> insert into DemoTable values(1001,88);
Query OK, 1 row affected (0.21 sec)
mysql> insert into DemoTable values(1000,89);
Query OK, 1 row affected (0.11 sec)
mysql> insert into DemoTable values(1000,67);
Query OK, 1 row affected (0.14 sec)
mysql> insert into DemoTable values(1000,90);
Query OK, 1 row affected (0.21 sec)
mysql> insert into DemoTable values(1001,91);
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 −

+-----------+--------------+
| StudentId | StudentMarks |
+-----------+--------------+
|      1000 |           78 |
|      1001 |           88 |
|      1000 |           89 |
|      1000 |           67 |
|      1000 |           90 |
|      1001 |           91 |
+-----------+--------------+
6 rows in set (0.00 sec)

Following is the query to find the average of rows with the same ID −

mysql> select StudentId,avg(StudentMarks) from DemoTable group by StudentId;

This will produce the following output −

+-----------+-------------------+
| StudentId | avg(StudentMarks) |
+-----------+-------------------+
|      1000 |           81.0000 |
|      1001 |           89.5000 |
+-----------+-------------------+
2 rows in set (0.03 sec)

Updated on: 27-Sep-2019

416 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements