如何在MySQL中基于字段值求和?
要基于字段值求和,请使用聚合函数SUM()
和CASE语句。让我们首先创建一个表-
mysql> create table DemoTable(
Id int NOT NULL AUTO_INCREMENT PRIMARY KEY,
Price int,
isValidCustomer boolean,
FinalPrice int
);
使用插入命令在表中插入一些记录-
mysql> insert into DemoTable(Price,isValidCustomer,FinalPrice) values(20,false,40);mysql> insert into DemoTable(Price,isValidCustomer,FinalPrice) values(45,true,10);
mysql> insert into DemoTable(Price,isValidCustomer,FinalPrice) values(89,true,50);
mysql> insert into DemoTable(Price,isValidCustomer,FinalPrice) values(200,false,100);
使用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添加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中基于字段值求和? 的全部内容, 来源链接: utcz.com/z/355960.html