使用单个SQL语句检索两个COUNT

时间:2011-05-06 09:10:42

标签: sql count group-by

假设Table1具有c1列,其允许值为1或0.

如何使用单个查询检索0,1的数量?有可能吗?

抱歉,STUPID的提问方式。

我想把答案放在一行,而不是单列。

6 个答案:

答案 0 :(得分:3)

这是单个表/索引读取。子查询很可能有两个这样的读取

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

..它也是便携式的

答案 1 :(得分:2)

如果我理解正确,只需GROUP BY该列。

SELECT c1, count(*)
FROM Table1
GROUP BY c1;

答案 2 :(得分:2)

替代方式;

select
   sum(c1) as ones, 
   count(*) - sum(c1) as zeros
from
   Table1

答案 3 :(得分:1)

取决于您正在使用的DBMS。 在oracle中,以下是可能的:

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

答案 4 :(得分:0)

已经回答过,但总有(几乎)不止一种方法可以做到这一点。两个查询的联盟?

select count(*) from t1 where value='0' 
union
select count(*) from t1 where value='1' 

答案 5 :(得分:0)

  

从emp

中选择uid      

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 **