计算值的类别

时间:2018-05-19 10:24:38

标签: sql if-statement count distinct

我在可空列中有int个值v >= 0,我想计算列中Null,0,1和2+的出现次数如何有效地进行?

1 个答案:

答案 0 :(得分:1)

一种方法是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;