在Hive表中转置数据

时间:2017-03-09 11:57:08

标签: sql hive hiveql unpivot

我已经阅读了一些类似于这里的问题的答案,但它们都有些不同。我有一些数据位于蜂巢表中,我希望能够做的是获取2列并将它们移动/附加到我的数据集的底部。我想这样做,同时保留以前与该行相关的信息,并结合2个单独的日期字段。

我的数据看起来像这样

ID     Action   Date/Time of Action  Date of Issue  Issue
1111    TypeA   01/02/2016           05/04/2016     IssueA
1111    TypeB   01/03/2016           05/04/2016     IssueA
1111    TypeB   03/03/2016           05/04/2016     IssueA
1111    TypeC   28/03/2016           05/04/2016     IssueA
2222    TypeB   01/02/2016           30/03/2016     IssueA
2222    TypeB   05/03/2016           30/03/2016     IssueA
2222    TypeC   28/03/2016           30/03/2016     IssueA
3333    TypeA   07/01/2016           27/01/2016     IssueB
3333    TypeB   03/01/2016           27/01/2016     IssueB

我想要的是这个

ID      Action/Issue    Date-Time   Type
1111    TypeA           01/02/2016  Action
1111    TypeB           01/03/2016  Action
1111    TypeB           03/03/2016  Action
1111    TypeC           28/03/2016  Action
1111    IssueA          05/04/2016  Issue
2222    TypeB           01/02/2016  Action
2222    TypeB           05/03/2016  Action
2222    TypeC           28/03/2016  Action
2222    IssueA          30/03/2016  Issue
3333    TypeA           07/01/2016  Action
3333    TypeB           03/01/2016  Action
3333    IssueB          27/01/2016  Issue

我在这里看到了一些关于如何使用MAP和EXPLODE的例子,并试图使用它们但是我感到很困惑,它们似乎更多地涉及到旋转数据以使其更宽,而我想要去另一种方式。

有什么想法吗?

1 个答案:

答案 0 :(得分:0)

select      ID
           ,Action      as Action_Issue
           ,Action_Date as DT
           ,'Action'    as TYP

from        mytable

union all

select      ID
           ,Issue       as Action_Issue   
           ,Issue_date  as DT
           ,'Issue'     as TYP

from        mytable

group by    ID
           ,Issue
           ,Issue_date
;
+--------+------------------+------------+---------+
| _u1.id | _u1.action_issue |   _u1.dt   | _u1.typ |
+--------+------------------+------------+---------+
|   1111 | TypeA            | 2016-02-01 | Action  |
|   1111 | TypeB            | 2016-03-01 | Action  |
|   1111 | TypeB            | 2016-03-03 | Action  |
|   1111 | TypeC            | 2016-03-28 | Action  |
|   2222 | TypeB            | 2016-02-01 | Action  |
|   2222 | TypeB            | 2016-03-05 | Action  |
|   2222 | TypeC            | 2016-03-28 | Action  |
|   3333 | TypeA            | 2016-01-07 | Action  |
|   3333 | TypeB            | 2016-01-03 | Action  |
|   1111 | IssueA           | 2016-04-05 | Issue   |
|   2222 | IssueA           | 2016-03-30 | Issue   |
|   3333 | IssueB           | 2016-01-27 | Issue   |
+--------+------------------+------------+---------+