配置单元中的 Concat 字符串列

Concat String columns in hive

我需要连接 table 中的 3 列,比如 a、b、c。如果列的长度大于 0,那么我必须连接所有 3 列并将其存储为以下格式的另一列 d。

1:a2:b3:c

我尝试了以下查询,但我不确定如何继续,因为结果为空。

select a,b,c,
case when length(a) >0 then '1:'+a else '' end + case when length(b) > 0 then '2:'+b else '' end + case when length(c) > 0 then '3:'+c else '' end AS d
from xyz;

感谢帮助:)

使用concat()函数:

select a,b,c,
       concat(
              case when length(a)>0 then concat('1:',a) else '' end,
              case when length(b)>0 then concat('2:',b) else '' end,  
              case when length(c)>0 then concat('3:',c) else '' end 
             ) as d 
from (--test dataset
       select stack(4, 'a','b','c', --all
                      '','b','c',  --one empty
                      null,'b','c', --null
                      '','',''      --all empty
                   ) as (a,b,c) 
     )your_data;

结果:

OK
a       b       c       1:a2:b3:c
        b       c       2:b3:c
NULL    b       c       2:b3:c

耗时:0.284 秒,获取:4 行 - 最后一行为空

从 Hive 2.2.0 开始。您可以使用 || 运算符代替 concat:

select a,b,c,
       case when length(a)>0 then '1:'||a else '' end||
       case when length(b)>0 then '2:'||b else '' end|| 
       case when length(c)>0 then '3:'||c else '' end as d