使用存储过程的IF条件的MySQL总和查询
该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)
这是将一个字符串作为参数的存储过程" title="存储过程">存储过程-
mysql> delimiter //mysql> create procedure sp_GetSumWithPaymentMode11(PaymentMode varchar(200))
−> begin
−> select PaymentMode,sum(if(ModeOfPayment=PaymentMode,Amount,0)) as TotalAmount from SumWithIfCondition;
−> end //
mysql> delimiter ;
现在,您可以使用call命令来调用存储过程。
案例1-在线
查询如下-
mysql> call sp_GetSumWithPaymentMode11('Online');
以下是输出-
+-------------+-------------+| PaymentMode | TotalAmount |
+-------------+-------------+
| Online | 600 |
+-------------+-------------+
1 row in set (0.00 sec)
情况2-离线
查询如下-
mysql> call sp_GetSumWithPaymentMode11('Offline');
以下是输出-
+-------------+-------------+| PaymentMode | TotalAmount |
+-------------+-------------+
| Offline | 60 |
+-------------+-------------+
1 row in set (0.00 sec)
以上是 使用存储过程的IF条件的MySQL总和查询 的全部内容, 来源链接: utcz.com/z/335279.html