如何在 MySQL 中根据字段值进行求和?


若要根据字段值求和,请使用聚合函数 SUM() 和 CASE 语句。我们首先创建一个表 −

mysql> create table DemoTable
   (
   Id int NOT NULL AUTO_INCREMENT PRIMARY KEY,
   Price int,
   isValidCustomer boolean,
   FinalPrice int
   );
Query OK, 0 rows affected (0.23 sec)

使用 insert 命令在表中插入一些记录 −

mysql> insert into DemoTable(Price,isValidCustomer,FinalPrice) values(20,false,40);
Query OK, 1 row affected (0.09 sec)

mysql> insert into DemoTable(Price,isValidCustomer,FinalPrice) values(45,true,10);
Query OK, 1 row affected (0.16 sec)

mysql> insert into DemoTable(Price,isValidCustomer,FinalPrice) values(89,true,50);
Query OK, 1 row affected (0.09 sec)

mysql> insert into DemoTable(Price,isValidCustomer,FinalPrice) values(200,false,100);
Query OK, 1 row affected (0.06 sec)

使用 select 语句显示表中的所有记录 −

mysql> select *from DemoTable;

这将产生以下输出 −

+----+-------+-----------------+------------+
| Id | Price | isValidCustomer | FinalPrice |
+----+-------+-----------------+------------+
| 1  | 20    | 0               | 40         |
| 2  | 45    | 1               | 10         |
| 3  | 89    | 1               | 50         |
| 4  | 200   | 0               | 100        |
+----+-------+-----------------+------------+
4 rows in set (0.00 sec)

以下是对 SQL 查询以根据 MySQL 中的字段值求和。在这里,FinalPrice 将添加到 FALSE (0),而 PRICE 将添加到 TRUE(1) −

mysql> select sum(case when isValidCustomer=true then Price else FinalPrice end) as TotalPrice from DemoTable;

这将产生以下输出 −

+------------+
| TotalPrice |
+------------+
| 274        |
+------------+
1 row in set (0.00 sec)

更新于: 2019-07-30

321 查看

开启你的 职业生涯

完成课程,获得认证

开始学习
广告
© . All rights reserved.