I have a MSSQL query where I sum the value of columns. For an example;
select SUM(column_a), SUM(column_b)
from table c
group by c_id
Now I need to sum only positive numbers, ignore negative numbers. For an example:
Column A:
2
-2
4
2
The SUM function will give me result of 6 (2-2+4+2) What I need it to do is to ignore the negative number (-2) and give me result of 8 (2+4+2)
I have 8 columns where I need it.
To compute the absolute value of a number, use the ABS() function. This function takes a number as an argument and returns its value without the minus sign if there is one. The returned value will always be non-negative – zero for argument 0, positive for any other argument.
You can use sign to separate the values: select Sum( ( Sign( n ) + 1 ) / 2 * n ) as PositiveSum, Sum( -( Sign( n ) - 1 ) / 2 * n ) as NegativeSum from YourTableOData; Sign returns 1 , 0 or -1 depending on the sign of the input value.
The SQL Server SUM() function is an aggregate function that calculates the sum of all or distinct values in an expression. In this syntax: ALL instructs the SUM() function to return the sum of all values including duplicates. ALL is used by default.
To get the sum of a negative and a positive number, use the sign of the larger number and subtract. For example: (–7) + 4 = –3. 6 + (–9) = –3.
Use case
expressions to do conditional aggregation:
select sum(case when a > 0 then a else 0 end),
sum(case when b > 0 then b else 0 end)
...
from tablename
Add GROUP BY
if needed:
group by c_id
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With