计数值的类别

追问者

在可空列中intv >= 0,我想计算列中 Null、0、1 和 2+ 的出现次数如何有效地做到这一点?

戈登·利诺夫

一种方法是group by

select (case when col in (0, 1) then cast(col as varchar(255))
             else '2+'
        end) as grp, count(*)
from t
group by (case when col in (0, 1) then cast(col as varchar(255))
               else '2+'
          end)
order by min(col);

的确切语法cast()可能取决于数据库。这也假设所有值都是非负的。

您也可以将计数放在不同的列中:

select sum(case when val = 0 then 1 else 0 end) as cnt_0,
       sum(case when val = 1 then 1 else 0 end) as cnt_1,
       sum(case when val >= 2 then 1 else 0 end) as cnt_2pl
from t;

本文收集自互联网,转载请注明来源。

如有侵权,请联系[email protected] 删除。

编辑于
0

我来说两句

0条评论
登录后参与评论

相关文章