使用 MySQL 从另一列中具有对应重复值中添加记录
为此,可以使用聚合函数 SUM() 以及 GROUP BY 子句。让我们首先创建一个表 -
mysql> create table DemoTable -> ( -> Name varchar(20), -> Value int -> ); Query OK, 0 rows affected (2.08 sec)
使用 insert 命令在表中插入一些记录 -
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)
广告