views:

30

answers:

2

Hi,

sql column - trans_value contain both positive and negative value amount.

so i'm trying to figure out how do i set a sum of positive value and negative value aside, so that i can calculate the how much sum of positive and how much is sum of negative.

so in the end, i can minus both, positive - negative.

edit, i forgot to mention before that

there is also column name product id in same table, so

product_id | trans_value
1               200
1               250
1               -150
2               500
2               -300
3               200
3               -150

so i need to get sum of product id 1, display it out, then for 2, 3 and so on.

thanks

+3  A: 

If you just want to see the total for each product_id

SELECT product_id, SUM(trans_value)
FROM table
GROUP BY product_id
ORDER BY product_id

If you really need the positive and negative values seperately:

SELECT SUM(IF(trans_value<0;trans_value;0)) neg, SUM(IF(trans_value>0;trans_value;0)) pos
FROM table

Will put the sum of the negative values in neg, the sum of the positive values in pos. pos + neg will be the total sum.

Konerak
hi sorry, i forgot to mention earlier before, i edited my post, check pls thanks
damien
Edited the answer.
Konerak
is it possible to come up with php method?
damien
uh, `pos - neg` is not the total sum, the total sum is `pos + neg`.
Mark E
@Mark: thank you.
Konerak
A: 

SELECT SUM( trans_value ) AS sum FROM table WHERE trans_value > 0;

Chris
That will only sum the positives. OP asked for the negatives too.
Konerak