hive 合并第一个非空值,分层表SQL中的可变空值位置

vecaoik1  于 4个月前  发布在  Hive
关注(0)|答案(2)|浏览(77)

我有一个表,其中包含不同深度的空值:
| 昏暗|col1| col2| col3| col4|
| --|--|--|--|--|
| v| C| B|一|NULL|
| X|一|NULL| NULL| NULL|
| y| B|一|NULL| NULL|
| z| D| C| B|一|
有谁知道我如何写一个select语句来反转和折叠NULL值?把最右边的第一个值作为最左边的新值,实现这个转换:
| 昏暗|col1| col2| col3| col4|
| --|--|--|--|--|
| v|一|B| C| NULL|
| X|一|NULL| NULL| NULL|
| y|一|B| NULL| NULL|
| z|一|B| C| D|

goqiplq2

goqiplq21#

你可以将所有列用一些列连接起来,用一些常量替换NULL,比如'null',提取null部分,反转非null部分,再次将反转的非null与null连接起来,分割得到一个数组,现在你可以将数组元素作为列,不要忘记检查null并反转每个元素以正确地获得长度超过1个字符的值:

with 
test_data as (
select 'v' as dim, 'c' as col1, 'b' as col2,    'a' as col3,    NULL as col4 union all
select 'x', 'a', NULL,  NULL ,  NULL  union all
select 'y', 'b', 'a',   NULL ,  NULL  union all
select 'z', 'd', 'c',   'b',    'a'
)

select dim,
       case when reversed_array[0] = 'null' then null else reverse(reversed_array[0]) end as col1,
       case when reversed_array[1] = 'null' then null else reverse(reversed_array[1]) end as col2,
       case when reversed_array[2] = 'null' then null else reverse(reversed_array[2]) end as col3,
       case when reversed_array[3] = 'null' then null else reverse(reversed_array[3]) end as col4     
from
(
select dim,
split(
concat(
--all before |null
reverse(regexp_replace(concat_ws('|',nvl(col1,'null'), nvl(col2,'null'), nvl(col3,'null'), nvl(col4,'null')),'(\\|null)*','')),
--NULLs
regexp_extract(concat_ws('|',nvl(col1,'null'), nvl(col2,'null'), nvl(col3,'null'), nvl(col4,'null')),'((\\|null)*)$',1)
)
,'\\|') as reversed_array
from test_data
) s

字符串
测试结果:

dim     col1    col2    col3    col4    
v       a       b       c       NULL
x       a       NULL    NULL    NULL
y       a       b       NULL    NULL
z       a       b       c       d

xmq68pz9

xmq68pz92#

参见实施例

select *
  ,case when col1 is null then col1
        when col2 is null then col1
        when col3 is null then col2
        when col4 is null then col3
  else col4
  end col1
  ,case when col1 is null then col2
        when col2 is null then col2
        when col3 is null then col1
        when col4 is null then col2
  else col3
  end col2
  ,case when col1 is null then col3
        when col2 is null then col3
        when col3 is null then col3
        when col4 is null then col1
  else col2
  end col3
  ,case when col1 is null then col4
        when col2 is null then col4
        when col3 is null then col4
        when col4 is null then col4
  else col1
  end col4
from test

字符串
试验
| 昏暗|col1| col2| col3| col4| col1| col2| col3| col4|
| --|--|--|--|--|--|--|--|--|
| v| C| B|一|null|一|B| C| null|
| X|一|null| null| null|一|null| null| null|
| y| B|一|null| null|一|B| null| null|
| z| D| C| B|一|一|B| C| D|
| u| null| null| null| null| null| null| null| null|

相关问题