Kiberzauras Kiberzauras - 5 months ago 22
MySQL Question

Subtract values from sum depending on the value of another column

I have a mysql table with columns:

value - integer
type - integer


value
only can be positive integer,
type
can be
0
or
1


I need to sum this
value
, but the thing is that if
type
value is
1
i need to subtract this row
value
from my sum.

Is its possible to make without two queries?

Answer

You can try something like this, using if:

sum( if(`type` = 1, -1, 1) * `value` )

Or case:

sum( (case when `type` = 1 then -1 else 1 end) * `value` )