查找具有相同 ID 的行平均值的 MySQL 查询
我们先创建一个表 -
mysql> create table DemoTable ( StudentId int, StudentMarks int ); Query OK, 0 rows affected (0.83 sec)
使用 insert 命令在表中插入一些记录 -
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)
使用 select 语句显示表中的所有记录 -
mysql> select *from DemoTable;
这将生成以下输出 -
+-----------+--------------+ | StudentId | StudentMarks | +-----------+--------------+ | 1000 | 78 | | 1001 | 88 | | 1000 | 89 | | 1000 | 67 | | 1000 | 90 | | 1001 | 91 | +-----------+--------------+ 6 rows in set (0.00 sec)
以下查询用于查找具有相同 ID 的行平均值 -
mysql> select StudentId,avg(StudentMarks) from DemoTable group by StudentId;
这将生成以下输出 -
+-----------+-------------------+ | StudentId | avg(StudentMarks) | +-----------+-------------------+ | 1000 | 81.0000 | | 1001 | 89.5000 | +-----------+-------------------+ 2 rows in set (0.03 sec)
广告