查找不同科目学生的平均成绩,并在MySQL中仅显示最高平均成绩
为此,您可以使用子查询。让我们首先创建一个表:
mysql> create table DemoTable ( StudentName varchar(40), StudentMarks int ); Query OK, 0 rows affected (0.50 sec)
使用insert命令在表中插入一些记录:
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)
使用select语句显示表中的所有记录:
mysql> select *from DemoTable;
这将产生以下输出:
+-------------+--------------+ | StudentName | StudentMarks | +-------------+--------------+ | Adam | 56 | | Chris | 78 | | Adam | 89 | | Robert | 98 | | Chris | 65 | | Robert | 34 | +-------------+--------------+ 6 rows in set (0.00 sec)
以下是查找学生平均成绩并仅显示最高平均成绩的查询:
mysql> select max(avSal.StudentMarks) from (select avg(StudentMarks) as `StudentMarks` from DemoTable group by StudentName) as avSal;
这将产生以下输出:
+-------------------------+ | max(avSal.StudentMarks) | +-------------------------+ | 72.5000 | +-------------------------+ 1 row in set (0.09 sec)
广告