mysql中sum与if,case when 结合使用


1.sum与if结合使用

 

  如图:数据表中,count_money 字段可为正,可为负。为正表示收入,负表示支出。

统计总收入,总支出。

select sum(if(count_money > 0, count_money, 0)) as sum_receipt, sum(if(count_money<0, count_money, 0)) as sum_paid from tableName;

得到sum_receipt为总收入,sum_paid为总支出。

mysql 中if的用法:

if(expr1,expr2,expr3)

expr1 为条件

expr2 true时返回结果

expr3 false 返回结果

 

2.sum与case when 结合使用

 

 type 表示类型, 1为收入,2为支出

select sum(case when type = 1 then count_money else 0 end) as sum_receipt, sum(case when type = 2 then count_money else 0 end) as sum_paid from tableName;

得到sum_receipt为总收入,sum_paid为总支出。


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM