在 Hive 中转置许多列

Transposing many columns in Hive

全部, 有很多关于转置的问题,但找不到最好的 solution.So 发布另一个转置问题

我的数据是这种格式

> Customer| Status_A|Status_B|Status_C  
> 111|New | Null|New   
> 222|Old | Old |New   
> 333|Null| New |New 

我想要这种格式的结果

>Customer   Parameter   Status  
>111    A   New  
>111    B   Null  
>111    C   New  
>222    A   Old  
>222    B   Old  
>222    C   New  
>333    A   Null   
>333    B   New   
>333    C   New  

注- 1) 我有 50 列这样的
2)我真的不需要结果数据中的空行

正在寻找最有效的解决方案。谢谢

最简单的方法是使用巨人 union all:

select customer, 'A' as parameter, status_a as status from t where status_a is not null union all
select customer, 'B' as parameter, status_b from t where status_b is not null union all
. . .

这可能很难打字,因此我建议您在电子表格中或使用其他 SQL 查询生成代码。

以上要求为每列扫描一次 table。有时更快的方法使用 cross join:

select t.customer, p.parameter,
       (case p.parameter
            where 'a' then status_a
            where 'b' then status_b
            . . .
        end) as status
from t cross join
     (select 'a' as parameter union all
      select 'b' union all
      . . .
     ) p;

要消除 NULLs,请将其设为子查询并使用 where status is not NULL.