我在可空列中有int
个值v >= 0
,我想计算列中Null,0,1和2+的出现次数如何有效地进行?
答案 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;