hive sql列转行
时间: 2023-07-12 13:29:22 浏览: 129
在Hive中,可以使用`UNION ALL`和`CASE WHEN`语句来实现列转行的功能。
假设有如下表格`test`:
```
id name value1 value2 value3
1 John A B C
2 Mary D E NULL
3 Bob F NULL NULL
```
要将每行中的`value1`、`value2`、`value3`列转换为多行,可以使用以下SQL语句:
```
SELECT id, name, 'value1' AS col_name, value1 AS col_value FROM test WHERE value1 IS NOT NULL
UNION ALL
SELECT id, name, 'value2' AS col_name, value2 AS col_value FROM test WHERE value2 IS NOT NULL
UNION ALL
SELECT id, name, 'value3' AS col_name, value3 AS col_value FROM test WHERE value3 IS NOT NULL
ORDER BY id, col_name;
```
执行以上SQL语句后,得到的结果如下:
```
id name col_name col_value
1 John value1 A
1 John value2 B
1 John value3 C
2 Mary value1 D
2 Mary value2 E
3 Bob value1 F
```
其中每个`SELECT`语句查询出一个列,并且使用`CASE WHEN`语句将列名和列值存储在`col_name`和`col_value`列中。最后使用`UNION ALL`将多个结果集合并,并使用`ORDER BY`对结果进行排序。
阅读全文