Oracle 11g Pivot函數實現行轉列

來源:互聯網
上載者:User

標籤:

先上文法規範:
SELECT ....FROM <table-expr>   PIVOT     (      aggregate-function(<column>)      FOR <pivot-column> IN (<value1>, <value2>,..., <valuen>)        ) AS <alias>WHERE .....
通過一個例子說明其用法:
select * from (select salary, department_id from employee) pivot(sum(salary) as sum_sal for(department_id) in (10,20,30));
10_sum_sal 20_sum_sal 30_sum_sal
370000    155000370000
在這個例子中,工資按照指定部門做聚集後,成為獨立的列顯示出來。有幾個部門,就有幾列;而總是只有一行。即是說,達到了行轉列的效果。這種效果的報表在BI/DW應用中很常見。
注意:IN語句是必須的。也就是說,在運行SQL之前必須知道department_id

再進一步,按照多個列作行轉列
select * from (select salary, department_id,manager from employee) pivot(sum(salary) for(department_id,manager) in ((10,28),(10,null),(20,null)));
10_28   10_null 20_null
27000010000090000
這個SQL查詢按照指定部門和經理的組合彙總後的工資。相當於按照兩個維度來做聚集。

兩個pivot,這時列數增加1倍。但是for() in()內容需要保持一致,否則Oracle無法確定你的列名,列的資料類型。
求各部門總工資和平均工資
select * from (select salary, department_id from employee) pivot(sum(salary) sumsal, avg(salary) avgsal for(department_id) in (10,20,30));
10_sum  10_avg  20_sum 20_avg   30_sum  30_avg
3700007400015500077500370000185000

Oracle 11g 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.