Syntax error Finding average marks of students for different subjects and display only the highest average marks in MySQL

Finding average marks of students for different subjects and display only the highest average marks in MySQL



For this, you can use subquery. Let us first create a table −

mysql> create table DemoTable
(
   StudentName varchar(40),
   StudentMarks int
);
Query OK, 0 rows affected (0.50 sec)

Insert some records in the table using insert command −

mysql> insert into DemoTable values('Adam',56);
Query OK, 1 row affected (0.14 sec)
mysql> insert into DemoTable values('Chris',78);
Query OK, 1 row affected (0.13 sec)
mysql> insert into DemoTable values('Adam',89);
Query OK, 1 row affected (0.13 sec)
mysql> insert into DemoTable values('Robert',98);
Query OK, 1 row affected (0.19 sec)
mysql> insert into DemoTable values('Chris',65);
Query OK, 1 row affected (0.11 sec)
mysql> insert into DemoTable values('Robert',34);
Query OK, 1 row affected (0.20 sec)

Display all records from the table using select statement −

mysql> select *from DemoTable;

This will produce the following output −

+-------------+--------------+
| StudentName | StudentMarks |
+-------------+--------------+
| Adam        |           56 |
| Chris       |           78 |
| Adam        |           89 |
| Robert      |           98 |
| Chris       |           65 |
| Robert      |           34 |
+-------------+--------------+
6 rows in set (0.00 sec)

Following is the query to find average marks of students and display only the highest average marks −

mysql> select max(avSal.StudentMarks)
from (select avg(StudentMarks) as `StudentMarks` from DemoTable group by StudentName) as avSal;

This will produce the following output −

+-------------------------+
| max(avSal.StudentMarks) |
+-------------------------+
|                 72.5000 |
+-------------------------+
1 row in set (0.09 sec)
Updated on: 2019-10-04T06:32:27+05:30

995 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements