如何在Oracle中使用countIf()函数

6

我该如何选择一个变量,使其输出与Excel函数相同:

COUNTIFS(A1:D1,"<25", A1:D1, ">16")?

即,计算我的四个字段中的值在16到25之间出现的次数。

3个回答

8
你可以使用 count() case表达式来完成此操作。请注意: case 有一个可选的 else 子句;如果未使用,则默认的 else “value”为 null 。Count仅计算非空值,因此可以将这些观察结果组合起来编写紧凑的代码。计算的内容并不重要;因此, case 表达式可以返回数字(通常为1,但0同样有效,并且将给出相同的结果,因为计数的是值而不是求和)-但你也可以在case表达式中使用字符串,例如'x'或日期。只是为了说明这一点,我将使用一个字符串。
select count( case when col > 16 and col < 25 then 'x' end ) as ct from your_table;

这里的your_table是您的表格名称,col是包含值的的名称,ct是结果列的名称(满足您条件的值的计数标签)。
当然,在数据库中,您可以更轻松地获得相同的结果:
select count(*) as ct from your_table where col > 16 and col < 25;

请注意,这些值在一列中。

如果您的表格有四个列并且有很多行,并且所有列中的所有值都是数字,并且您想要添加一列显示每行严格介于16和25之间的数值数量,则解决方案不同(但使用相同的思路):

select col1, col2, col3, col4, 
       case when col1 > 16 and col1 < 25 then 1 else 0 end +
       case when col2 > 16 and col2 < 25 then 1 else 0 end +
       case when col3 > 16 and col3 < 25 then 1 else 0 end +
       case when col4 > 16 and col4 < 25 then 1 else 0 end    as ct
from   my_table;

4

您可以在SQL查询中使用case来完成此操作:

select sum(case when col between 16 and 25 then 1 else 0 end)
from t;

请注意,SQL 中的 between 是包含的而不是排除的。因此,根据您的代码逻辑:
select sum(case when col > 16 and col < 25 then 1 else 0 end)
from t;

0

假设你有一个名为'user_table'的表,其中一些用户的'status'active (code-11),而其他用户则是inactive (code-22)。您可以使用以下sql计算活动和非活动用户。

select count(case when status = 11 then 1 end) u_active, count(case when status = 22 then 1 end) u_inactive, from user_table;


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接