unpivot 行转列顾名思义就是将多列转换成1列中去
案例:现在有一个水果表,记录了4个季度的销售数量,现在要将每种水果的每个季度的销售情况用多行数据展示。 创建表和数据 - <span style="background-color: white;">create table Fruit(id int,name varchar(20), Q1 int, Q2 int, Q3 int, Q4 int);
-
- insert into Fruit values(1,'苹果',1000,2000,3300,5000);
- insert into Fruit values(2,'橘子',3000,3000,3200,1500);
- insert into Fruit values(3,'香蕉',2500,3500,2200,2500);
- insert into Fruit values(4,'葡萄',1500,2500,1200,3500);
- select * from Fruit</span>
复制代码
列转行查询 - <span style="background-color: white;">select id , name, jidu, xiaoshou from Fruit unpivot (xiaoshou for jidu in (q1, q2, q3, q4) )
- </span>
复制代码
注意: unpivot没有聚合函数,xiaoshou、jidu字段也是临时的变量
同样不使用unpivot也可以实现同样的效果,只是sql语句会很长,而且执行速度效率也没有前者高 - <span style="background-color: white;">select id, name ,'Q1' jidu, (select q1 from fruit where id=f.id) xiaoshou from Fruit f
- union
- select id, name ,'Q2' jidu, (select q2 from fruit where id=f.id) xiaoshou from Fruit f
- union
- select id, name ,'Q3' jidu, (select q3 from fruit where id=f.id) xiaoshou from Fruit f
- union
- select id, name ,'Q4' jidu, (select q4 from fruit where id=f.id) xiaoshou from Fruit f
- </span>
复制代码
|