使用存储过程的带有 IF 条件的 MySQL 求和查询
Sum() 是 MySQL 中的聚合函数。您可以使用带有 if 条件的 sum 查询。为了理解带有 if 条件的 sum 查询,创建一张表。
创建表的查询 -
mysql> create table SumWithIfCondition −> ( −> ModeOfPayment varchar(100) −> , −> Amount int −> ); Query OK, 0 rows affected (1.60 sec)
使用插入命令插入一些记录到表中。查询如下 -
mysql> insert into SumWithIfCondition values('Offline',10); Query OK, 1 row affected (0.21 sec) mysql> insert into SumWithIfCondition values('Online',100); Query OK, 1 row affected (0.16 sec) mysql> insert into SumWithIfCondition values('Offline',20); Query OK, 1 row affected (0.13 sec) mysql> insert into SumWithIfCondition values('Online',200); Query OK, 1 row affected (0.16 sec) mysql> insert into SumWithIfCondition values('Offline',30); Query OK, 1 row affected (0.11 sec) mysql> insert into SumWithIfCondition values('Online',300); Query OK, 1 row affected (0.17 sec)
使用 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)
以下是将一个字符串作为参数的存储过程 -
mysql> delimiter // mysql> create procedure sp_GetSumWithPaymentMode11(PaymentMode varchar(200)) −> begin −> select PaymentMode,sum(if(ModeOfPayment=PaymentMode,Amount,0)) as TotalAmount from SumWithIfCondition; −> end // Query OK, 0 rows affected (0.32 sec) mysql> delimiter ;
现在,您可以使用 call 命令调用存储过程。
案例 1 - 对于 Online
查询如下 -
mysql> call sp_GetSumWithPaymentMode11('Online');
以下是输出 -
+-------------+-------------+ | PaymentMode | TotalAmount | +-------------+-------------+ | Online | 600 | +-------------+-------------+ 1 row in set (0.00 sec) Query OK, 0 rows affected (0.01 sec)
案例 2 - 对于 Offline
查询如下 -
mysql> call sp_GetSumWithPaymentMode11('Offline');
以下是输出 -
+-------------+-------------+ | PaymentMode | TotalAmount | +-------------+-------------+ | Offline | 60 | +-------------+-------------+ 1 row in set (0.00 sec) Query OK, 0 rows affected (0.01 sec)
广告