Reputation: 69
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.
Upvotes: 6
Views: 16981
Reputation: 44796
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
Upvotes: 12
Reputation: 2142
select sum(column_a), sum(column_b) from table c where column_a>0 and column_b>0 group by c_id
Upvotes: 0
Reputation: 3123
Cant you just not select
them in your query with a simple WHERE
clause?
WHERE Number > 0;
Upvotes: 2