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为总支出。

posted @ 2019-11-28 19:15  子夜的流星  阅读(4129)  评论(0编辑  收藏  举报