使用MySQL从另一列中相应的重复值添加记录
为此,可以使用聚合函数SUM()和GROUP BY子句。让我们首先创建一个表 –
mysql> create table DemoTable
-> (
-> Name varchar(20),
-> Value int
-> );
Query OK, 0 rows affected (2.08 sec)
使用插入命令在表中插入一些记录 –
mysql> insert into DemoTable values('Chris',50);
Query OK, 1 row affected (0.15 sec)
mysql> insert into DemoTable values('David',90);
Query OK, 1 row affected (0.19 sec)
mysql> insert into DemoTable values('Chris',60);
Query OK, 1 row affected (0.11 sec)
mysql> insert into DemoTable values('Bob',100);
Query OK, 1 row affected (0.15 sec)
mysql> insert into DemoTable values('David',80);
Query OK, 1 row affected (0.21 sec)
使用select语句显示表中的所有记录 –
mysql> select * from DemoTable;
这将产生以下输出 –
+-------+-------+
| Name | Value |
+-------+-------+
| Chris | 50 |
| David | 90 |
| Chris | 60 |
| Bob | 100 |
| David | 80 |
+-------+-------+
5 rows in set (0.00 sec)
以下是从另外一列的重复值添加记录的查询 –
mysql> select Name,sum(Value) as GrandTotal from DemoTable group by Name;
这将产生以下输出 –
+-------+------------+
| Name | GrandTotal |
+-------+------------+
| Chris | 110 |
| David | 170 |
| Bob | 100 |
+-------+------------+
3 rows in set (0.03 sec)
阅读更多:MySQL 教程