unpivot()函数
需要Oracle版本大于等于11g
--创建表
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;
--列转行查询
select id, name, jidu, xiaoshou from Fruit unpivot(xiaoshou for jidu in(q1, q2, q3, q4))
注意:
unpivot没有聚合函数,xiaoshou、jidu字段也是临时的变量。等同于下面的SQL:
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