Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to minus negative values in sum?

I am using SUM() function. But SUM() sums the negative value in the column. In a column if the value is positive then it should be added and for negative values should be substracted and not added as the SUM()

20.00
20.00
20.00
20.00
-20.00
20.00
20.00
40.00
20.00
20.00
20.00
20.00
20.00
-20.00
-20.00
20.00

sum() should return 220 and not 440. Is returning 440.

like image 796
hrishi Avatar asked Dec 03 '22 00:12

hrishi


2 Answers

To subtract negative numbers rather than add them you would use SUM(ABS(col)) but just to check this is what you actually need example results below.

WITH YourTable(col) AS
(
SELECT 2 UNION ALL
SELECT -5 
)
SELECT 
       SUM(ABS(col)) AS [SUM(ABS(col))],
       SUM(col) AS [SUM(col)]
FROM YourTable

Returns

SUM(ABS(col)) SUM(col)
------------- -----------
7             -3
like image 171
Martin Smith Avatar answered Dec 29 '22 22:12

Martin Smith


SELECT SUM(ABS(Column_Name)) FROM Table_Name;

like image 41
vchitta Avatar answered Dec 29 '22 20:12

vchitta