I have one table and one column in it. There is 15 rows (integers). I want to count the positive numbers and negative numbers, and also sum of total numbers in one query.
Can any one help me?
Upvotes: 1
Views: 239
Reputation: 166606
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
Upvotes: 1
Reputation: 15849
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.
Upvotes: 3
Reputation: 70354
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
Upvotes: 1
Reputation: 432662
I'll give you psudeo code to help you with your homework.
3 aggregates:
Upvotes: 1