【发布时间】:2011-05-06 09:10:41
【问题描述】:
假设 Table1 有 c1 列,其允许值为 1 或 0。
如何通过单个查询检索 0、1 的数量?有可能吗?
对不起,愚蠢的提问方式。
我希望答案在一行,而不是一列。
【问题讨论】:
假设 Table1 有 c1 列,其允许值为 1 或 0。
如何通过单个查询检索 0、1 的数量?有可能吗?
对不起,愚蠢的提问方式。
我希望答案在一行,而不是一列。
【问题讨论】:
这是一个单一的表/索引读取。子查询很可能有两次这样的读取
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**
【讨论】: