星空网 > 软件开发 > 数据库

Oracle行转列(使用pivot函数)

在日常使用中,经常遇到这样的情况,需要将数据库中行转化成列显示,如

Oracle行转列(使用pivot函数)Oracle行转列(使用pivot函数)转化为Oracle行转列(使用pivot函数)
这个时候,我们就需要使用pivot函数
百度后,参考网址http://www.2cto.com/database/201501/367164.html ,完成了以下操作
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,其用法如下

pivot(聚合函数 for 列名 in(类型))
--其中 in(‘’) 中可以指定别名,in中还可以指定子查询,比如 select distinct ranking from temp


当然也可以不使用pivot函数,使用下面的语句同样可以实现效果

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;


当然Oracle还提供了unpivot函数,实现列转换的操作,项目中还没有使用,也就没有细细研究了。
参考地址:http://blog.csdn.net/xb12369/article/details/39554935

解决长久以来遇到的问题,心情舒畅,遂记录于此,方便后来查看

 




原标题:Oracle行转列(使用pivot函数)

关键词:oracle

*特别声明:以上内容来自于网络收集,著作权属原作者所有,如有侵权,请联系我们: admin#shaoqun.com (#换成@)。

Y Combinator:https://www.ikjzd.com/w/2124
HyperSuggest_关键词工具:https://www.ikjzd.com/w/2126
旺集科技:https://www.ikjzd.com/w/2127
无忧达_51 Delivery:https://www.ikjzd.com/w/2128
旺集科技_海外仓:https://www.ikjzd.com/w/2129
关键词工具Merchantwords:https://www.ikjzd.com/w/213
长治婚庆女司仪和主持人:https://www.vstour.cn/a/366176.html
北京丰台区水上乐园哪家好玩?:https://www.vstour.cn/a/366177.html
相关文章
我的浏览记录
最新相关资讯
海外公司注册 | 跨境电商服务平台 | 深圳旅行社 | 东南亚物流