如何在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)
热门推荐
10 八一幼儿祝福语大全简短
11 公司乔迁食堂祝福语简短
12 婚礼结束聚餐祝福语简短
13 儿媳买车妈妈祝福语简短
14 毕业送礼老师祝福语简短
15 同事辞职正常祝福语简短
16 恭贺新婚文案祝福语简短
17 金店立秋祝福语简短英文
18 婆婆高寿祝福语大全简短