So I want to turn negative value's into a 0. I found 2 solutions that do exactly the same:
SUM(IF(ordered_item.amount < 0, 0, ordered_item.amount)) as purchases
And
SUM(CASE WHEN ordered_item.amount < 0 THEN 0 ELSE ordered_item.amount END) as purchases
They give me both the same result, but which would give me the best performance? And is there maybe a simpler solution to turn negatives into 0
.
select name, (case when (sum(case when TransTypeName like 'credit%' then amount else 0 end) - sum(case when TransTypeName like 'Debit%' then amount ) else 0 end)) *5/100)<0 then 0 else (sum(case when TransTypeName like 'credit%' then amount else 0 end) - sum(case when TransTypeName like 'Debit%' then amount ) else 0 ...
So to answer your question, yes you can use the decimal datatype to store negative decimal numbers.
Introduction to MySQL INT typeAn integer can be zero, positive, and negative.
An alternate approach you could use is the GREATEST() function.
SUM(GREATEST(ordered_item.amount, 0)) as purchases
You can define the field as "unsigned" so no conversion would be required
CREATE TABLE ordered_item (
order_id INT UNSIGNED NOT NULL AUTO_INCREMENT,
amount INT UNSIGNED NOT NULL,
PRIMARY KEY (`order_id `)
);
https://dev.mysql.com/doc/refman/5.0/en/integer-types.html
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With