Reputation: 111
In a table named "table1" contains only 1 column named "column1" contains only -1 and 1. how to write a query to get count of -1 and 1 in the column1 by giving the alias names using single query.
I should print like,
positive 10
negative 5
I am just able to print the count of number by writing the query like
select count(*) from table1 group by column1;
but how to give the alias name to both numbers as positive and negative.
Upvotes: 1
Views: 917
Reputation: 1974
you could use "sub-queries" like this:
SELECT (select count(*) from table1 group by column1 having column1>0) POAITIVE,
(select count(*) from table1 group by column1 having column1<0) NEGATIVE;
Upvotes: 1
Reputation: 1
SELECT
'Positive' AS [Pos/Neg],
SUM(CASE WHEN [column1] = 1 THEN 1 ELSE 0 END) AS [Count]
FROM table1
UNION
SELECT
'Negative' AS [Pos/Neg],
SUM(CASE WHEN [column1] = -1 THEN 1 ELSE 0 END) AS [Count]
FROM table1
Upvotes: 0
Reputation: 164154
You can GROUP BY column1
and use a CASE
expression that returns 'positive' or 'negative':
SELECT CASE column1
WHEN 1 THEN 'positive'
WHEN -1 THEN 'negative'
END sign,
COUNT(*) counter
FROM table1
GROUP BY column1
But if there is a case that there are no positives or no negatives it is better to use conditional aggregation with UNION ALL
:
SELECT 'positive' sign, COUNT(CASE WHEN column1 = 1 THEN 1 END) counter FROM table1
UNION ALL
SELECT 'negative', COUNT(CASE WHEN column1 = -1 THEN 1 END) FROM table1
See a simplified demo.
Upvotes: 1
Reputation: 258
Please try with the below Query and it should be work as you expected.
SELECT
CASE
WHEN COLUMN1 = -1 THEN 'NEGATIVE'
ELSE 'POSITIVE'
END AS RESULT,
COUNT(1) AS COUNT
FROM
TABLE1
GROUP BY
CASE
WHEN COLUMN1 = -1 THEN 'NEGATIVE'
ELSE 'POSITIVE'
END
Upvotes: 0