将列名称转换为Hive中的行

时间:2019-03-05 08:02:54

标签: hive

我在Hive中有一张桌子。我必须将列名转换为行。我的表格如下-

+---------+---------+---------+ |Table 1 | Table 2 | Table 3 | +---------+---------+---------+ | A | D | F | +---------+---------+---------+ | B | E | | +---------+---------+---------+ | C | | | +---------+---------+---------+

我需要将其转换为具有2列的表。第一列将具有标题->表名,第一列中的值将是旧表的列名。最终输出应如下所示-

+-----------+--------+
|Table Name |   Val  |
+-----------+--------+
|  Table 1  |    A   |
+-----------+--------+
|  Table 1  |    B   |
+-----------+--------+
|  Table 1  |    C   |
+-----------+--------+
|  Table 2  |    D   |
+-----------+--------+
|  Table 2  |    E   |
+-----------+--------+
|  Table 3  |    F   |
+-----------+--------+

我被困住了。如何使用Hive获取所需的输出?

1 个答案:

答案 0 :(得分:1)

使用UNION ALL,为第一列提供与您的列名相对应的静态值:

CREATE TABLE new_table as
select * from 
(
select 'Table 1' as Table_Name, Table_1 as Val from your_table
UNION ALL
select 'Table 2' as Table_Name, Table_2 as Val from your_table
UNION ALL
select 'Table 3' as Table_Name, Table_3 as Val from your_table
) s where Val is not NULL
;