set @total_balance=0;
select total_balance=if(a.transaction_type='+c') then total_balance=total_balance+a.tran_amount
else if(a.transaction_type='-p'or '-r') then total_balance=total_balance-a.tran_amount
END
from lib_user_account a
where employee_Id='1004';
答案 0 :(得分:2)
SUM(IF(a.transaction_type='+c', a.tran_amount, -a.tran_amount))
答案 1 :(得分:1)
最好在查询中使用sum函数,因为zerkms已经提到但是要回答关于如何在MYSQL中使用用户定义变量的问题,您可以在查询中以下列方式使用它
select
@total_balance:=if(a.transaction_type='+c', @total_balance+a.tran_amount, if(a.transaction_type='-p' or a.transaction_type='-r', @total_balance-a.tran_amount, a.tran_amount))
from
lib_user_account a
join
(select @total_balance:=0) userVar
where
employee_Id='1004';