Reputation: 951
Assume Table1 has c1 column for which allowed values are either 1 or 0.
How to retrieve number of 0s, 1s with a single query? Is it possible?
sorry, STUPID way of questioning.
I wanted the answer in a single row, not single column.
Upvotes: 2
Views: 135
Reputation: 128
select uid from emp
UID 0 0 0 1 1 1 1 0 0
select distinct
(select count(uid) from emp where uid = 0) zeros_total,
(select count(uid) from emp where uid = 1) ones_total
from
emp
O/P **zeros_total 5 ones_total 4**
Upvotes: 0
Reputation: 175806
Alternate way;
select
sum(c1) as ones,
count(*) - sum(c1) as zeros
from
Table1
Upvotes: 2
Reputation: 21
Depends on the DBMS you're using. In oracle the following is possible:
select
(select count(status) from table1 where status = 0) as status_0,
(select count(status) from table1 where status = 1) as status_1
from dual
Upvotes: 1
Reputation: 432271
This is a single table/index read. Subqueries will most likely have two such reads
SELECT
COUNT(CASE status WHEN 1 THEN 1 ELSE NULL END) AS Ones,
COUNT(CASE status WHEN 0 THEN 1 ELSE NULL END) AS Zeros
FROM
MyTable
..and it's portable too
Upvotes: 3
Reputation: 172
Already been answered, but there's always (nearly) more than one way to do it. Union of two queries?
select count(*) from t1 where value='0'
union
select count(*) from t1 where value='1'
Upvotes: 0
Reputation: 16304
If I understand this correctly, just GROUP BY
that column.
SELECT c1, count(*)
FROM Table1
GROUP BY c1;
Upvotes: 2