Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MSSQL Query - Sum only positive numbers

Tags:

sql

sql-server

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.

like image 741
TheDon Avatar asked Sep 16 '15 09:09

TheDon


People also ask

How do I get only positive values in SQL?

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.

How do you display the sum of positive and negative numbers in SQL?

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.

How do I sum unique values in SQL?

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.

How do you find the sum of negative and positive numbers?

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.


1 Answers

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
like image 172
jarlh Avatar answered Sep 29 '22 15:09

jarlh