0

我已经阅读了一个关于此的线程,但是当我尝试它时,我无法让它工作。我想像这样计算表格中的所有男性和女性:

Select 
count(case when substr(id,1, 1) in (1,2) then 1 else 0 end) as M, 
count(case when substr(id,1, 1) in (3,4) then 1 else 0 end) as F 
from users where activated=1

这个想法是一个 id 以 1 或 2 开头的用户是男性
我的表有 3 个男性条目,并且 2 个被激活并返回(case 语句不起作用

M,F
2,2

任何输入将不胜感激

id    activated
123   1
234   0
154   1
4

3 回答 3

4

你应该SUM改用。COUNT将计算所有非空值。

Select 
SUM(case when substr(id,1, 1) in (1,2) then 1 else 0 end) as M, 
SUM(case when substr(id,1, 1) in (3,4) then 1 else 0 end) as F 
from users where activated=1
于 2012-10-12T08:15:09.647 回答
2

COUNT将为您提供非空值的数量,无论它们是什么。试试SUM吧。

于 2012-10-12T08:14:22.220 回答
1

如果您的 Oracle 版本是 10g 或更高版本,作为替代方案,您可以使用regexp_countfunction。我假设该ID列是number数据类型,因此在示例中它varchar2使用函数显式转换为数据类型TO_CHAR。如果ID列的数据类型是varchar2char则不需要任何类型的数据类型转换。

这是一个例子:

SQL> create table M_F(id, activated) as(
  2    select 123,   1 from dual union all
  3    select 234,   0 from dual union all
  4    select 434,   1 from dual union all
  5    select 154,   1 from dual
  6  );

Table created

SQL> select sum(regexp_count(to_char(id), '^[12]')) as M
  2      ,  sum(regexp_count(to_char(id), '^[34]')) as F
  3    from M_F
  4   where activated = 1
  5  ;

         M          F
---------- ----------
         2          1

演示

于 2012-10-12T09:09:50.270 回答