Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to SQL SUM with condition

Tags:

sql

sum

I have a transaction table and want to calculate based on the type of transaction. How to?

Table:

id | amount | type
--------------------
01 | 230    | IncomingTransfer
02 | 100    | OutcomingTransfer
03 | 20     | IncomingTransfer

Logic:

SELECT SUM(amount)
IF IncomingTransfer
    + 230
    + 20
ELSE IF OutcomingTransfer
    - 100

Total amount: +150
like image 833
Ricardo Avatar asked Apr 07 '26 08:04

Ricardo


1 Answers

AS simple as my sqlfiddle shows:

select
sum(CASE WHEN type = 'IncomingTransfer' THEN amount ELSE -amount END) as totalsum
from t;
like image 135
MrSimpleMind Avatar answered Apr 09 '26 22:04

MrSimpleMind



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!