Search This Blog

Sum of only Positive Values of a column and sum of negative value of a column in SQL

Sum of only Positive Values of a column and sum of negative value of a column


While creating a Reports one of my colleagues asked me that he has to display sum of only Positive values of a column in a new column and sum of only negative value of a column in a new column Although it can be done easily in SSRS Report also
but his requirement was through sql code.

So below is the Sample code with Solutions

--Creating a test table with Both Position and Negative Values

create table value
(Testvalues int)

insert into value values(1),(-2),(3),(-4),(5),(-6)

Select * from Values

If you will calculate the total of positive values it will be 9 and for negative values it is -12


SO below is the Query
select
  SUM(case when Testvalues>0 then Testvalues else 0 end)SumPositiveValue,
       SUM(case when Testvalues<0 then Testvalues else 0 end)SumNegativeValues
       from value


SumPositiveValue SumNegativeValues
9                           -12

3 comments:

  1. Hats off to your presence of mind..I really enjoyed reading your blog. I really appreciate your information which you shared with us.
    Php course in chennai

    ReplyDelete
  2. Great info. I love all the posts, I really enjoyed,
    nice post and site, good work!
    I would like more information about this, because it is very nice.
    quickbooks training in hyderabad

    ReplyDelete
  3. It is extremely nice to see the greatest details presented in an easy and understanding manner. positive singles

    ReplyDelete