views:

89

answers:

4

i have one table and one column in this.there is 15 data(integer).i want to count

positive numbers and negative numbers

and also

sum of total numbers

in one query . can any one help me .........

+1  A: 

I'll give you psudeo code to help you with your homework.

3 aggregates:

  • SUM
  • SUM (CASE < 0)
  • SUM (CASE > 0)
gbn
+1  A: 
select (select sum(mycolumn) from mytable where mycolumn > 0) as positive_sum,
       (select sum(mycolumn) from mytable where mycolumn < 0) as negative_sum,
       sum(mycolumn) as total_sum
from   mytable
Daren Thomas
OP said: _i want to count positive numbers and negative numbers_ you SUM them
KM
+1  A: 

Try this

SELECT  SUM(CASE WHEN Col > 0 THEN 1 ELSE 0 END) AS Pos,
     SUM(CASE WHEN Col < 0 THEN 1 ELSE 0 END) AS Neg,
     SUM(Col) AS Tot
FROM    Table
astander
if OP wants count of Pos and Neg, you need to change _THEN Col ELSE 0_ to _THEN 1 ELSE 0_
KM
true, i will change it now
astander
+3  A: 

Or...

SELECT  
     COUNT(CASE WHEN Col > 0 THEN 1 END) AS NumPositives,
     COUNT(CASE WHEN Col < 0 THEN 1 END) AS NumNegatives,
     SUM(Col) AS Tot
FROM  TableName;

Or you could consider using SIGN(Col), which gives 1 for positive numbers and -1 for negative numbers.

Rob Farley
I initially up-voted for this, but took back the up vote, when I noticed the COUNT(), I was thinking SUM(). After testing, I see it works, but couldn't up-vote unless question was edited, so I edited.
KM
I used COUNT because it fits the problem most closely. By having no ELSE clause, I only count the ones that meet the criteria.
Rob Farley