首页 > 解决方案 > 在 HIVE 中转置数据

问题描述

我在 Hive 中有以下数据集,我想将行转换为列。

顾客 地位 数量
25 有薪酬的 5
25 N 付费 2
67 打开 12
67 有薪酬的 4
45 N 付费 3
45 打开 2

我想在转置后有一个新表,它只显示客户的一行,状态的多列,例如

顾客 有薪酬的 N 付费 打开
25 5 2 0
67 4 0 12
45 0 3 2

我尝试了一些在 Internet 上找到的示例,但无法使其正常工作。在这里,为了简单起见,我只列出了三个状态,但实际上,我可以拥有更多。

在 SAS 中,我曾经做过以下事情:

proc transpose
   data = imputtable;
   out = outputtable;
   by customer;
   id status;
   var quantity;
run;

SAS 获取所有现有状态并将它们转换为列。我希望在 Hive 中做同样的事情。

问候,

马西奥

标签: sqlhivehiveqltranspose

解决方案


使用条件聚合:

select Customer, 
       sum(case when Status = 'Paid'   then Quantity else 0 end) as Paid     ,
       sum(case when Status = 'N Paid' then Quantity else 0 end) as `N Paid` ,
       sum(case when Status = 'Open'   then Quantity else 0 end) as Open
 from table
group by Customer

推荐阅读