开发者

mysql fetch sum php

开发者 https://www.devze.com 2023-01-06 00:16 出处:网络
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 m

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


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.


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

0

精彩评论

暂无评论...
验证码 换一张
取 消