【发布时间】:2018-05-19 10:24:37
【问题描述】:
我在可空列中有int 值v >= 0,我想计算列中出现 Null、0、1 和 2+ 的次数如何有效地做到这一点?
【问题讨论】:
标签: sql if-statement count distinct
我在可空列中有int 值v >= 0,我想计算列中出现 Null、0、1 和 2+ 的次数如何有效地做到这一点?
【问题讨论】:
标签: sql if-statement count distinct
一种方法是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;
【讨论】:
sum(case when val is NULL then 1 else 0 end) as cnt_null 不见了