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

Popular posts from this blog

linux - Does gcc have any options to add version info in ELF binary file? -

android - send complex objects as post php java -

charts - What graph/dashboard product is facebook using in Dashboard: PUE & WUE -