如何在 MySQL 中根据字段值求和?
mysqlmysqli database更新于 2025/9/11 17:48:17
要根据字段值求和,请使用聚合函数 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)
以下是根据 MySQL 中的字段值进行求和的查询。这里,如果为 FALSE (0),则添加 FinalPrice,如果为 TRUE(1),则添加 PRICE −
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)
相关文章
有用资源
mysql 参考教程 - 该教程包含有关 mysql 的更多信息:https://www.cainiaomax.com/mysql/

