有条件的MySQL Sum查询?
该Sum()
是在MySQL聚合函数。您可以将和查询与if条件一起使用。要了解带有if条件的求和查询,让我们创建一个表。
创建表的查询-
mysql> create table SumWithIfCondition −> ( −> ModeOfPayment varchar(100) −> , −> Amount int −> );
使用insert命令在表中插入一些记录。查询如下-
mysql> insert into SumWithIfCondition values('Offline',10); mysql> insert into SumWithIfCondition values('Online',100); mysql> insert into SumWithIfCondition values('Offline',20); mysql> insert into SumWithIfCondition values('Online',200); mysql> insert into SumWithIfCondition values('Offline',30); mysql> insert into SumWithIfCondition values('Online',300);
使用select语句显示表中的所有记录。查询如下-
mysql> select *from SumWithIfCondition;
以下是输出-
+---------------+--------+ | ModeOfPayment | Amount | +---------------+--------+ | Offline | 10 | | Online | 100 | | Offline | 20 | | Online | 200 | | Offline | 30 | | Online | 300 | +---------------+--------+ 6 rows in set (0.00 sec)
这是带有if条件的求和查询。
情况1-如果是在线付款方式
查询如下-
mysql> select sum(if(ModeOfPayment = 'Online',Amount,0)) as TotalAmount from SumWithIfCondition;
以下是输出-
+-------------+ | TotalAmount | +-------------+ | 600 | +-------------+ 1 row in set (0.00 sec)
情况2- 如果是离线付款方式
查询如下-
mysql> select sum(if(ModeOfPayment = 'Offline',Amount,0)) as TotalAmount from SumWithIfCondition;
以下是输出-
+-------------+ | TotalAmount | +-------------+ | 60 | +-------------+ 1 row in set (0.00 sec)