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为总支出。
2、sum与case when 结合使用
select
sum(case when count_money > 0 then count_money else 0 end) as sum_receipt,
sum(case when count_money < 0 then count_money else 0 end) as sum_paid
from tableName;
3、总结
- 可以发现,case when和if函数的功能是相同的,if的使用更简洁直观
- 条件复杂时,使用case when,条件简单时,使用if()
本文介绍了在SQL查询中,如何使用IF和CASE WHEN函数来统计表格中正负金额分别对应的总收入和总支出。通过示例,展示了IF函数在条件简单时的简洁性,以及CASE WHEN在处理复杂条件时的灵活性。这两种方法在财务数据分析和数据库操作中非常实用。
2021

被折叠的 条评论
为什么被折叠?



