Hive函数之count

准备数据:

create table t1( a int);
insert into t1 (a) values (1);
insert into t1 (a) values (2);
insert into t1 (a) values (3);
insert into t1 (a) values (NULL);

1.count(*)与count(1)
这两种写法计算结果相同,都是计算总行数包括字段值为NULL的行

select count(*) from t1;
select count(1) from t1;

这两条sql都返回4
2.count(expr)
count可以自定义表达式完成一些高级统计功能,如下:

select count(a) from t1;

《Hive函数之count》 image.png

count(a)将返回a字段不为NULL的行数,所以为3。

select count(a>1) from t1;

《Hive函数之count》 image.png

这条sql返回3。

最后看下count distinct用法

select count(distinct a) from t1;

《Hive函数之count》 image.png

count(distinct a)去重统计也会排除字段为NULL的值。

count distinct还可以写更复杂的表达式:

select count(distinct case when a>1 then a else NULL end)  from t1

《Hive函数之count》 image.png

    原文作者:pptb
    原文地址: https://www.jianshu.com/p/61b9ae271cdc
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞