您可以SUM()使用GROUP BY命令的聚合函数来获取另一列中每个不同值的总和。为了理解上述概念,让我们创建一个表。创建表的查询如下:mysql> create table SumOfEveryDistinct
-> (
-> Id int not null,
-> Amount int
-> );
使用insert命令在表中插入一些记录。查询如下:mysql> insert into SumOfEveryDistinct values(10,100);
mysql> insert into SumOfEveryDistinct values(11,200);
mysql> insert into SumOfEveryDistinct values(12,300);
mysql> insert into SumOfEveryDistinct values(10,400);
mysql> insert into SumOfEveryDistinct values(11,500);
mysql> insert into SumOfEveryDistinct values(12,600);
mysql> insert into SumOfEveryDistinct values(10,700);
mysql> insert into SumOfEveryDistinct values(11,800);
mysql> insert into SumOfEveryDistinct values(12,900);
使用select语句显示表中的所有记录。查询如下:mysql> select *from SumOfEveryDistinct;
以下是输出:+----+--------+
| Id | Amount |
+----+--------+
| 10 | 100 |
| 11 | 200 |
| 12 | 300 |
| 10 | 400 |
| 11 | 500 |
| 12 | 600 |
| 10 | 700 |
| 11 | 800 |
| 12 | 900 |
+----+--------+
9 rows in set (0.00 sec)
这是求和另一列中每个不同值的查询:mysql> select Id, sum(Amount) as TotalSum from SumOfEveryDistinct
-> group by Id;
以下是输出:+----+----------+
| Id | TotalSum |
+----+----------+
| 10 | 1200 |
| 11 | 1500 |
| 12 | 1800 |
+----+----------+
3 rows in set (0.00 sec)