如何从一个字符串列中拆分值

时间:2019-08-12 19:04:40

标签: sql hive

我有带字符串列的HIVE表,在一列中有多个值,我想将这些值分成几列。 这是示例列值。

enter image description here

最终结果应如下所示 enter image description here

我使用了split函数,因为列中的值不在同一位置,我在列中得到的值是错误的,是否有任何函数基于其标记值来获取值

1 个答案:

答案 0 :(得分:1)

您需要使用 regexp_extract 函数并保持匹配的 regular expression 并提取值。

Regular expression:

lanes=>"(.*?)" //literal match for lanes=>" and capture until next following occurance " 
                and keep it in first capture group

Example:

with cte as (--sample data
    select stack(2,string('lanes=>"2","txt_mid"=>"0"'),
                    string('"is_in"=>"parksville"'))as(c1)) 
    select regexp_extract(c1,'lanes=>"(.*?)"',1)lanes,
            regexp_extract(c1,'"txt_mid"=>"(.*?)"',1)txt_mid 
        from cte;

Result:

lanes   txt_mid
2       0

如果您要缺失数据记录的值,请使用case-when-then语句检查字段的长度,如果 0 < / strong>,则记录的值为null