sql - MySQL add and subtract to a total sum, based on content of a second column -
is possible summation of column considers second columns content?
what want second statement:
select * thetable; +------------+-------------+ | type | value | +------------+-------------+ | plusitive | 11 | +------------+-------------+ | negative | 7 | +------------+-------------+ | negative | 3 | +------------+-------------+ select sum_based_on_whether_type_is_plusitive_or_negative(value) thetable; +----------------------------------------------------------------+ | sum_based_on_whether_type_is_plusitive_or_negative(value) | +----------------------------------------------------------------+ | 1 | +----------------------------------------------------------------+
so string 'plusitive' mean multiply value 1 , 'negative' mean multiply value -1 before adding sum.
anyone know how it? know table layout not optimal task, altering not option. solution implemented in stored procedure.
you can use case
expression inside aggregate function determine if value positive or negative:
select sum(case `type` when 'plusitive' value when 'negative' value * -1 end) total thetable;
see sql fiddle demo
Comments
Post a Comment