Hive中count统计包含空值的实现方法
解决SQL中NULL值的统计问题
问题原因
count(income_band)会自动忽略该列的NULL值,所以当income_band为NULL时,这部分行不会被计入统计结果,导致NULL分组的数量显示为0。
解决方案
方法1:使用count(*)统计所有行
count(*)会统计分组内的所有行(包括income_band为NULL的行),分组后会自动将NULL作为一个独立分组返回对应数量:
select year, income_band, count(*) from income_dataset where year = "2017" group by income_band, year
方法2:使用count(1)替代count(列名)
count(1)的效果和count(*)一致,因为1是常量,不会为NULL,所以会统计所有行:
select year, income_band, count(1) from income_dataset where year = "2017" group by income_band, year
方法3:单独统计NULL值(可选)
如果需要明确区分非NULL和NULL的统计结果,可以用UNION ALL合并两个查询:
-- 统计income_band为NULL的行 select year, 'NULL' as income_band, count(*) from income_dataset where year = "2017" and income_band is null union all -- 统计income_band非NULL的行 select year, income_band, count(income_band) from income_dataset where year = "2017" and income_band is not null group by income_band, year
内容的提问来源于stack exchange,提问作者Dave Diggler
相关产品推荐
相关产品推荐

