繁体   English   中英

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

[英]Retrieving two COUNTs using a single SQL statement

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

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

对不起,STUPID的提问方式。

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

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

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

..它也是便携式的

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

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

替代方式;

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

取决于您正在使用的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

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

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM