【SQL相关】Hive中空值与Null的判断及处理

1.空值与null的区别

        null没有被分配任何值或对象,表示这个字段没有被赋值或者值是未知的,占空间,不会被count()函数统计;

        空值表示这个字段被赋了一个空的值,不占空间,会被count()函数统计。

2.空值与null的判断

        null和”(空值)在SQL中的筛选过滤条件是不一样的,is null 识别不了 ”,同样地,” 也识别不了 null 。

2.1 null判断

--筛选null
select * from table where a is null
--筛选非null
select * from table where a is not null

2.2 空值判断

--筛选空值
select * from table where a = ''
--筛选非空值
select * from table where a  ''

--或者

--筛选空值
select * from table where length(a) = 0
--筛选非空值
select * from table where length(a)  0

2.3 null与空值判断

--筛选null与空值
select * from table where a is null and a = ''
--筛选非null与非空值
select * from table where a is not null and a  ''

--或者

--筛选null与空值
select * from table where nvl(a,'') = ''
--筛选非null与非空值
select * from table where nvl(a,'')  ''

3.空值与null的处理

3.1 null处理

nvl函数

nvl(expr1,expr2)

例如:nvl(a,0)

如果a字段值为null,那么null转化为0这个值,如果a字段值不为null,则显示a本来的值。

拓展–nvl2(expr1,expr2,expr3)

例如:nvl2(a,0,1)

如果a字段值为null,那么null转化为0这个值,如果a字段值不为null,则转化为1这个值。

3.2 空值处理

        hive本身没有replace函数,可以用translate和regexp_replace函数代替。

translate(expr1,expr2,expr3)

例如:translate(a,”,0)

将a字段的空值替换为0

regexp_replace(expr1,正则表达式,expr2)

例如:regexp_replace(a,”[\\s]+|[\u3000]+”,0)

将a字段的空值替换为1([\\s]+|[\u3000]+是正则)


        对于null的处理其实也可以使用translate和regexp_replace函数。

translate(a,null,0)

regexp_replace(nvl(a,””),”[\\s]+|[\u3000]+”,0)

 

本文来自网络,不代表协通编程立场,如若转载,请注明出处:https://net2asp.com/1468ea2a5a.html