unpivot函数是列转行函数,用来实现对数据的逆透视,语法如下:
unpivot [{INCLUDE_NULLS|EXCLUDE_NULLS}]
( {column|(column[,column]...)}
FOR column|(column[,column]...)}
in
({column|(column[,column]...)} [as {literal|(literal[,literal]...)}])
)
函数说明:
INCLUDE_NULLS:要转换的列值为null时,转换的时候保留null值,不对null进行过滤
EXCLUDE_NULLS:要转换的列值为null时,转换的时候对null要进行过滤,默认值为EXCLUDE_NULLS
Unpivot函数里包含的三部分内容说明如下:
Unpivot [{INCLUDE_NULLS|EXCLUDE_NULLS}]
(
Unpivot_clause
--新增加的列名,该列存储被转换列的列值
Unpivot_for_clause --新增加的列名,该列存储被转换列的列名
Unpiovt_in_clause --要被转换的列,这些列的列值是相兼容的
)
示例如下:
create table t(name varchar(40),chinese int,math
int);
insert into t values(‘张三’,90,100);
insert into t values(‘李四’,88,99);
原表查询结果:
+--------+----------+---------+
| name | chinese
| math |
+--------+----------+---------+
| 张三 | 90 |
100 |
| 李四 | 88 | 99 |
+--------+----------+---------+
2 rows in set
使用unpivot转换的结果:
select * from
t unpivot(score for course in(chinese,math));
+--------+----------+---------+
| name | course
| score |
+--------+----------+---------+
| 张三 | chinese | 90 |
| 张三 | math | 100 |
| 李四 | chinese | 88 |
| 李四 | math
| 99 |
+--------+----------+---------+
4 rows in set




