【问题标题】:Replace empty string in hive- Nvl and COALESCE tried替换 hive 中的空字符串 - Nvl 和 COALESCE 已尝试
【发布时间】:2018-09-19 11:26:10
【问题描述】:

如何用其他值替换空字符串(长度为 0 )?已使用 NvlCOALESCE 但两者都不会替换为替换值,因为该值不为空。我可以使用case 语句,但如果有的话,我会寻找一个内置函数。

【问题讨论】:

    标签: sql hive null hiveql


    【解决方案1】:

    在 Hive 中,空字符串被视为通常的可比较值,而不是 NULL。这就是为什么没有内置函数的原因。

    使用case语句:

    case when col='' or col is null then 'something' else col end
    

    【讨论】:

      【解决方案2】:

      由于您有空字符串,所以当我们使用 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  |
          +-----------+--+
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2012-02-21
        • 2016-07-29
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-01-04
        • 2010-10-31
        相关资源
        最近更新 更多