配置单元中的concat字符串列

6ljaweal  于 2021-06-24  发布在  Hive
关注(0)|答案(1)|浏览(345)

我需要把表中的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;

感谢您的帮助:)

qni6mghb

qni6mghb1#

使用 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

相关问题