James Privett
James Privett

Reputation: 1109

SQL - Counting a column twice

I have a table that has a column called 'status'. This can be set to 0 or 1

Is it possible for me to count both the 0's and 1's in a single query?

Thanks in advance

James

Upvotes: 4

Views: 3583

Answers (2)

ean5533
ean5533

Reputation: 8994

SELECT SUM(CASE WHEN status = 0 THEN 1 ELSE 0 END) AS 'number of zeroes',
       SUM(CASE WHEN status = 1 THEN 1 ELSE 0 END) AS 'number of ones'
FROM yourtable;

Upvotes: 9

Yuck
Yuck

Reputation: 50855

Yes, just group on the value of status:

SELECT status, COUNT(*)
FROM yourtable
GROUP BY status

That will give you exactly two rows since the value can only be 0 or 1, and the COUNT(*) column will be the number of times each status value appears in the table.

Upvotes: 9

Related Questions