Oracle中1个行转列例子

来源:互联网 发布:c语言的头文件是什么 编辑:程序博客网 时间:2024/06/13 10:25
create table temp as(
select '四川省' nation ,'成都市' city,'第一' ranking from dual union all
select '四川省' nation ,'绵阳市' city,'第二' ranking from dual union all
select '四川省' nation ,'德阳市' city,'第三' ranking from dual union all
select '四川省' nation ,'宜宾市' city,'第四' ranking from dual union all
select '湖北省' nation ,'武汉市' city,'第一' ranking from dual union all
select '湖北省' nation ,'宜昌市' city,'第二' ranking from dual union all
select '湖北省' nation ,'襄阳市' city,'第三' ranking from dual
);

select * from (select nation,city,ranking from temp) pivot (max(city) for ranking in ('第一' as 第一,'第二' AS 第二,'第三' AS 第三,'第四' AS 第四));

这样就顺利的实现了操作,其中关键函数pivot,其用法如下: pivot(聚合函数 for 列名 in(类型))
--其中 in('') 中可以指定别名,xml 类型的时候可以使用any 关键字和子查询,返回的结果是xml结构的。

当然也可以不使用pivot函数,使用下面的语句同样可以实现效果   
select nation,
max(decode(ranking, '第一', city, '')) as 第一,
max(decode(ranking, '第二', city, '')) as 第二,
max(decode(ranking, '第三', city, '')) as 第三,
max(decode(ranking, '第四', city, '')) as 第四
from temp group by nation;

racle 行转列pivot 、列转行unpivot 的sql语句总结
http://blog.csdn.net/xiaokui_wingfly/article/details/42419207?_t=t

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));
select id , name, jidu, xiaoshou from fruit unpivot (xiaoshou for jidu in (q1 as' c1', q2 as 'c2', q3 as 'c3', q4 as 'c4'));
原创粉丝点击