hive怎么行转列
时间: 2023-08-02 15:26:49 浏览: 59
在Hive中,可以使用Lateral View表达式将行转列。具体实现步骤如下:
1. 使用Lateral View表达式将每个数组元素转化为一个单独的行。
例如,以下是一个包含数组的表:
```
+----+---------------------+
| id | colors |
+----+---------------------+
| 1 | ["red","green","blue"]|
| 2 | ["yellow","orange"] |
+----+---------------------+
```
要将每个颜色转换为单独的行,可以使用以下查询:
```
SELECT id, color
FROM table_name
LATERAL VIEW explode(colors) color_table AS color;
```
这将生成以下输出:
```
+----+--------+
| id | color |
+----+--------+
| 1 | red |
| 1 | green |
| 1 | blue |
| 2 | yellow |
| 2 | orange |
+----+--------+
```
2. 使用Group By语句将行转换为列。
使用上面的查询结果作为子查询,可以使用Group By语句将每个ID的颜色转换为一个单独的行。例如:
```
SELECT id,
max(CASE WHEN row_num = 1 THEN color END) AS color1,
max(CASE WHEN row_num = 2 THEN color END) AS color2,
max(CASE WHEN row_num = 3 THEN color END) AS color3
FROM
(
SELECT id, color, row_number() OVER (PARTITION BY id ORDER BY color) AS row_num
FROM
(
SELECT id, color
FROM table_name
LATERAL VIEW explode(colors) color_table AS color
) a
) b
GROUP BY id;
```
这将生成以下输出:
```
+----+--------+--------+--------+
| id | color1 | color2 | color3 |
+----+--------+--------+--------+
| 1 | red | green | blue |
| 2 | yellow | orange | NULL |
+----+--------+--------+--------+
```
这样就把原本的行转换成了列。
阅读全文