【发布时间】:2018-09-19 11:26:10
【问题描述】:
如何用其他值替换空字符串(长度为 0 )?已使用 Nvl 和 COALESCE 但两者都不会替换为替换值,因为该值不为空。我可以使用case 语句,但如果有的话,我会寻找一个内置函数。
【问题讨论】:
如何用其他值替换空字符串(长度为 0 )?已使用 Nvl 和 COALESCE 但两者都不会替换为替换值,因为该值不为空。我可以使用case 语句,但如果有的话,我会寻找一个内置函数。
【问题讨论】:
在 Hive 中,空字符串被视为通常的可比较值,而不是 NULL。这就是为什么没有内置函数的原因。
使用case语句:
case when col='' or col is null then 'something' else col end
【讨论】:
由于您有空字符串,所以当我们使用 coalesce 或 nvl 时,只有当我们在数据中有 null 值 时才有效。这些函数不适用于空字符串。
使用空字符串:
hive> select coalesce(string(""),"1");
+------+--+
| _c0 |
+------+--+
| |
+------+--+
hive> select nvl(string(""),"1");
+------+--+
| _c0 |
+------+--+
| |
+------+--+
空值:
hive> select coalesce(string(null),"1");
+------+--+
| _c0 |
+------+--+
| 1 |
+------+--+
hive> select nvl(string(null),"1");
+------+--+
| _c0 |
+------+--+
| 1 |
+------+--+
尝试alter the table并添加此属性
TBLPROPERTIES('serialization.null.format'='')
如果这个属性没有将空字符串显示为空字符串,那么我们需要使用case/if 语句来替换空字符串。
你可以使用if statement
if(boolean testCondition, T valueTrue, T valueFalseOrNull)
hive> select if(length(trim(<col_name>))=0,'<replacement_val>',<col_name>) from <db>.<tb>;
示例:
hive> select if(length(trim(string("")))=0,'1',string("col_name"));
+------+--+
| _c0 |
+------+--+
| 1 |
+------+--+
hive> select if(length(trim(string("1")))=0,'1',string("col_name"));
+-----------+--+
| _c0 |
+-----------+--+
| col_name |
+-----------+--+
【讨论】: