如何使用条件进行 SQL SUM [英] How to SQL SUM with condition
本文介绍了如何使用条件进行 SQL SUM的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个交易表,想根据交易类型进行计算.怎么做?
I have a transaction table and want to calculate based on the type of transaction. How to?
表格:
id | amount | type
--------------------
01 | 230 | IncomingTransfer
02 | 100 | OutcomingTransfer
03 | 20 | IncomingTransfer
逻辑:
SELECT SUM(amount)
IF IncomingTransfer
+ 230
+ 20
ELSE IF OutcomingTransfer
- 100
Total amount: +150
推荐答案
像我的sqlfiddle 显示:
AS simple as my sqlfiddle shows:
select
sum(CASE WHEN type = 'IncomingTransfer' THEN amount ELSE -amount END) as totalsum
from t;
这篇关于如何使用条件进行 SQL SUM的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文