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

猜你喜欢

转载自www.cnblogs.com/zhangxiaoj/p/11953036.html
今日推荐