为此,可以将聚合函数SUM()与GROUP BY子句一起使用。让我们首先创建一个表-
create table DemoTable -> ( -> Name varchar(20), -> Value int -> );
使用插入命令在表中插入一些记录-
insert into DemoTable values('Chris',50); insert into DemoTable values('David',90); insert into DemoTable values('Chris',60); insert into DemoTable values('Bob',100); insert into DemoTable values('David',80);
使用select语句显示表中的所有记录-
select * from DemoTable;
这将产生以下输出-
+-------+-------+ | Name | Value | +-------+-------+ | Chris | 50 | | David | 90 | | Chris | 60 | | Bob | 100 | | David | 80 | +-------+-------+ 5 rows in set (0.00 sec)
以下是从另一列的重复值中添加记录的查询-
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)