Oracle行轉列(使用pivot函數)

來源:互聯網
上載者:User

標籤:

在日常使用中,經常遇到這樣的情況,需要將資料庫中行轉化成列顯示,如

轉化為這個時候,我們就需要使用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函數)

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.