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為總支出。