mysql fetch sum php

我怕爱的太早我们不能终老 提交于 2019-12-11 02:58: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 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


回答1:


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.




回答2:


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



来源:https://stackoverflow.com/questions/3205513/mysql-fetch-sum-php

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!