MySQL 查询来找到具有相同列值字段的总和?
为此使用 GROUP BY 子句。我们首先创建一个表 -
mysql> create table sumOfFieldsDemo -> ( -> Id int NOT NULL AUTO_INCREMENT PRIMARY KEY, -> ClientSerialNumber varchar(100), -> ClientCost int -> ); Query OK, 0 rows affected (0.50 sec)
以下是使用 insert 命令在表中插入一些记录的查询 -
mysql> insert into sumOfFieldsDemo(ClientSerialNumber,ClientCost) values('1111',450); Query OK, 1 row affected (0.16 sec) mysql> insert into sumOfFieldsDemo(ClientSerialNumber,ClientCost) values('2222',550); Query OK, 1 row affected (0.15 sec) mysql> insert into sumOfFieldsDemo(ClientSerialNumber,ClientCost) values('3333',150); Query OK, 1 row affected (0.64 sec) mysql> insert into sumOfFieldsDemo(ClientSerialNumber,ClientCost) values('3333',250); Query OK, 1 row affected (0.12 sec) mysql> insert into sumOfFieldsDemo(ClientSerialNumber,ClientCost) values('2222',1000); Query OK, 1 row affected (0.10 sec) mysql> insert into sumOfFieldsDemo(ClientSerialNumber,ClientCost) values('1111',1000); Query OK, 1 row affected (0.16 sec) mysql> insert into sumOfFieldsDemo(ClientSerialNumber,ClientCost) values('1111',500); Query OK, 1 row affected (0.17 sec) mysql> insert into sumOfFieldsDemo(ClientSerialNumber,ClientCost) values('4444',100); Query OK, 1 row affected (0.17 sec)
以下是使用 select 语句从表中显示所有记录的查询 -
mysql> select * from sumOfFieldsDemo;
将生成以下输出 -
+----+--------------------+------------+ | Id | ClientSerialNumber | ClientCost | +----+--------------------+------------+ | 1 | 1111 | 450 | | 2 | 2222 | 550 | | 3 | 3333 | 150 | | 4 | 3333 | 250 | | 5 | 2222 | 1000 | | 6 | 1111 | 1000 | | 7 | 1111 | 500 | | 8 | 4444 | 100 | +----+--------------------+------------+ 8 rows in set (0.00 sec)
以下是查找具有相同列值的字段总和的查询 -
mysql> select Id,ClientSerialNumber,SUM(ClientCost) AS TotalSum -> from sumOfFieldsDemo -> group by ClientSerialNumber;
将生成以下输出 -
+----+--------------------+----------+ | Id | ClientSerialNumber | TotalSum | +----+--------------------+----------+ | 1 | 1111 | 1950 | | 2 | 2222 | 1550 | | 3 | 3333 | 400 | | 8 | 4444 | 100 | +----+--------------------+----------+ 4 rows in set (0.00 sec)
广告