多行转多列多列转多行
多行转多列#创建新表 create table t1 (a integer comment "年份", b string comment "部门", c integer comment "绩效得分"); #向表中插入数据 insert into t1 (a,b,c) values (2014,"B",9),(2015,"A",8),(2014,"A",10),(2015,"B",7);
表预览如下:
现需要将该表多行转多列,转后的效果如下:
实现代码:
select t1.a, max(case when t1.b="A" THEN t1.c end) col_a, max(case when t1.b="B" then t1.c end) col_b from t1 group by t1.a;多列转多行
在上文的基础上,将多行转多列的结果作为源表,多列转多行。
#建表 create table t1_2 (a integer comment "年份", col_a integer comment "col_a", col_b integer comment "col_b"); #向表中插入数据 insert into t1_2 select t1.a as a, max(case when t1.b="A" THEN t1.c end) as col_a, max(case when t1.b="B" then t1.c end) as col_b from t1 group by t1.a; #多列转多行 select a,b,c from ( select a,"A" as b,col_a as c from t1_2 union all select a,"B" as b,col_b as c from t1_2 ) temp;



