gpt4 book ai didi

sql - 在Hive中转置许多列

转载 作者:行者123 更新时间:2023-12-02 21:30:59 26 4
gpt4 key购买 nike

全部,
关于转置有很多问题,但找不到最佳解决方案。因此发布另一个移置问题

我的数据是这种格式

> 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查询生成代码。

上面要求对表的每一列扫描一次。有时,更快的方法是使用 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;

要消除 NULL,请使其成为子查询并使用 where status is not NULL

关于sql - 在Hive中转置许多列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34265721/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com