MySQL中对应重复记录的SUM
mysqlmysqli database
首先我们创建一个表 −
mysql> create table DemoTable -> ( -> StudentName varchar(20), -> StudentMarks int -> ); Query OK, 0 rows affected (0.68 sec)
使用 insert 命令在表中插入一些记录 −
mysql> insert into DemoTable values('Chris',50); Query OK, 1 row affected (0.61 sec) mysql> insert into DemoTable values('David',70); Query OK, 1 row affected (0.23 sec) mysql> insert into DemoTable values('Chris',80); Query OK, 1 row affected (0.12 sec) mysql> insert into DemoTable values('David',90); Query OK, 1 row affected (0.24 sec)
使用 select 语句显示表中的所有记录 −
mysql> select * from DemoTable;
这将产生以下输出 −
+-------------+--------------+ | StudentName | StudentMarks | +-------------+--------------+ | Chris | 50 | | David | 70 | | Chris | 80 | | David | 90 | +-------------+--------------+ 4 rows in set (0.00 sec)
以下查询用于对相应的重复记录(即学生的成绩)求和 −
mysql> select StudentName,sum(StudentMarks) from DemoTable group by StudentName;
这将产生以下输出 −
+-------------+-------------------+ | StudentName | sum(StudentMarks) | +-------------+-------------------+ | Chris | 130 | | David | 160 | +-------------+-------------------+ 2 rows in set (0.00 sec)