sql - 在 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 中做同样的事情。
问候,
马西奥
解决方案
使用条件聚合:
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
推荐阅读
- typescript - 如何在连接打开一次的打字稿中建立mongodb NodeJS驱动程序连接
- javascript - 无法在文本框中显示当前日期
- mysql - Django:酒店预订数据库 start_date 和 end_date
- sql - 如果 IN 子句中的空表,Postgresql 查询会变慢
- python - 你可以在 python 中为 threading.local() 分配一个列表吗?
- python - 如何将多个标题 Excel 文档转换为 Pandas
- javascript - MongoDB 更新很多文档 Schema.Types.Mixed
- bash - 用于选择子目录中的 .c 文件的 bash 脚本
- elasticsearch - 将文本字段映射到 Elasticsearch 中的整数字段
- python - 我正在尝试为我的项目安装所有必需的模块