Oracle中"行轉列"的實現方式

來源:互聯網
上載者:User

標籤:

在報表的開發當中,難免會遇到行轉列的問題。

以Oracle中scott的emp為例,統計各職位的人員在各部門的人數分布情況,就可以用"行轉列":

scott的emp的未經處理資料為:

使用 "行轉列" 統計各職位的人員在各部門的分布人數後,資料為:

一、經典的實現方式

主要是利用decode函數、彙總函式(如max、sum等)、group by分組實現的

select t.job, count(decode(t.deptno, ‘10‘, 1)) as "10(DEPTNO)",       count(decode(t.deptno, ‘20‘, 1)) as "20(DEPTNO)",       count(decode(t.deptno, ‘30‘, 1)) as "30(DEPTNO)",       count(decode(t.deptno, ‘40‘, 1)) as "40(DEPTNO)"  from scott.emp t  group by t.job;

二、PIVOT

Oracle 11g後,出現PIVOT,更簡便地實現“行轉列”。使用前,需確定資料庫環境大於11g,最好也確認下生產環境的資料庫是否大於11g,避免項目後期出現狀況。

with tmp_tab as(    select t.job, t.deptno      from scott.emp t)select * from tmp_tab t pivot(count(1) for deptno in (10, 20, 30, 40));

三、PIVOT XML

使用經典的方法和PIVOT方法,DEPTNO的參數是硬式編碼。而通過PIVOT XML能解決這一問題,使分列條件可以是動態。但,輸出的是XML的CLOB的格式。目前,Java讀取PIVOT XML CLOB貌似比較困難(本人沒有成功讀取,可見下文描述,如有知曉者,請知悉)。

with tmp_tab as(    select t.job, t.deptno      from scott.emp t)select * from tmp_tab t pivot xml (count(1) for deptno in (select deptno from scott.dept));

本文轉自:http://www.cnblogs.com/nick-huang/p/3836061.html

Oracle中"行轉列"的實現方式

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.