标签:
在日常使用中,经常遇到这样的情况,需要将数据库中行转化成列显示,如
with 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(聚合函数 for 列名 in(类型))
--其中 in(‘’) 中可以指定别名,in中还可以指定子查询,比如 select distinct ranking from temp
with 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 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;
标签:
原文地址:http://www.cnblogs.com/xiaoganggis/p/4618108.html