我该如何选择一个变量,使其输出与Excel函数相同:
COUNTIFS(A1:D1,"<25", A1:D1, ">16")?
即,计算我的四个字段中的值在16到25之间出现的次数。
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;
您可以在SQL查询中使用case
来完成此操作:
select sum(case when col between 16 and 25 then 1 else 0 end)
from t;
between
是包含的而不是排除的。因此,根据您的代码逻辑:select sum(case when col > 16 and col < 25 then 1 else 0 end)
from t;
假设你有一个名为'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;