如何在 HIVE 中从长结构变为宽结构?

How to go from long to wide structure in HIVE?

我有一个如下所示的配置单元数据data in long format

我想将其重组为如下所示 data in wide format

我的看起来像这样my latest attempt

这是我用过的代码。我想去掉所有的 NULL,并将所有月份合并为一年下的一行。

select carrier, year, month,

max(case when month =1 then quantity end) as jan,
max(case when month =2 then quantity end) as feb,
max(case when month =3 then quantity end) as mar,
max(case when month =4 then quantity end) as apr,
max(case when month =5 then quantity end) as may,
max(case when month =6 then quantity end) as jun,
max(case when month =7 then quantity end) as jul,
max(case when month =8 then quantity end) as aug,
max(case when month =9 then quantity end) as sep,
max(case when month =10 then quantity end) as oct,
max(case when month =11 then quantity end) as nov,
max(case when month =12 then quantity end) as dec

from (select final_month.*, row_number() over 
(partition by carrier, year order by carrier, year) from final_month) 
final_month group by carrier, year, month;

这是我一直在使用的所有参考资料 link link

谢谢!

从 select 中删除 month 并分组。我相信你想要 SUM,而不是 max(),但你当然更了解数据:

select carrier, year, 
sum(case when month =1 then quantity end) as jan,
sum(case when month =2 then quantity end) as feb,
sum(case when month =3 then quantity end) as mar,
sum(case when month =4 then quantity end) as apr,
sum(case when month =5 then quantity end) as may,
sum(case when month =6 then quantity end) as jun,
sum(case when month =7 then quantity end) as jul,
sum(case when month =8 then quantity end) as aug,
sum(case when month =9 then quantity end) as sep,
sum(case when month =10 then quantity end) as oct,
sum(case when month =11 then quantity end) as nov,
sum(case when month =12 then quantity end) as dec
from ...
group by carrier, year