一个sql而不是2个用于计数

时间:2012-10-12 08:11:10

标签: sql oracle

我已经阅读了一个关于此问题的帖子,但是当我尝试它时,我无法使其成功。 我想从一张桌子上算出所有的男性和女性:

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

这意味着具有以1或2开头的id的用户是男性 我的表有3个男性条目,2个被激活并返回(案例陈述不起作用

M,F
2,2

任何输入都将不胜感激

id    activated
123   1
234   0
154   1

3 个答案:

答案 0 :(得分: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

答案 1 :(得分:2)

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

答案 2 :(得分:1)

如果您的Oracle版本为10g或更高版本,则可以使用regexp_count功能。我假设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

Demo