wm_concat函數簡單說就是行轉列顯示。
?
轉自: http://christy-fang.iteye.com/blog/1299850
首先讓我們來看看這個神奇的函數 wm_concat (列名),該函數可以把列值以","號分隔起來,并顯示成一行,接下來上例子。
準備測試數據
?
SQL> create? table ?test(id number,name varchar2(20));
SQL> insert into test values(1,'a');
SQL> insert into test values(1,'b');
SQL> insert into test values(1,'c');
SQL> insert into test values(2,'d');
SQL> insert into test values(2,'e');
?
SQL> commit;
?
效果1 : 行轉列
?
SQL> select wm_concat(name) from test;
WM_CONCAT(NAME)
-------------------------------------------------------------------------
a,b,c,d,e
?
效果2: 把結果里的逗號替換成"|"
?
SQL> select replace(wm_concat(name),',','|') from test;
REPLACE(WM_CONCAT(NAME),',','|')
-----------------------------------------------------------------------
a|b|c|d|e
?
?
效果3:按ID分組合并name
?
SQL> select id,wm_concat(name) name from test group by id;
ID NAME
---------- ------------------------------
1 a,b,c
2 d,e
?
懶人擴展用法:
案例:我要寫一個視圖,類似"create or replace view as select 字段1,...字段50 from tablename" ,基表有50多個字段,要是靠手工寫太麻煩了,有沒有什么簡便的方法?
當然有了,看我如果應用wm_concat來讓這個需求變簡單
?
SQL> select 'create or replace view as select '|| wm_concat(column_name) || ' from dept'from user_tab_columns where table_name='DEPT';
'CREATEORREPLACEVIEWASSELECT'||WM_CONCAT(COLUMN_NAME)||'FROMDEPT'
--------------------------------------------------------------------------------
create or replace view as select DEPTNO,DNAME,LOC from dept
?
注意: 1. wm_concat 是ORACLE內部函數,沒有對外公布,也就是說,你可以使用,但是如果發生什么問題ORACLE概不負責。
? ? ? ? ? 2.該函數在oracle10g下使用是正常的,但在oracle11g下,使用會有問題;在11g下,該方法有個替代函數,listagg()。
更多文章、技術交流、商務合作、聯系博主
微信掃碼或搜索:z360901061

微信掃一掃加我為好友
QQ號聯系: 360901061
您的支持是博主寫作最大的動力,如果您喜歡我的文章,感覺我的文章對您有幫助,請用微信掃描下面二維碼支持博主2元、5元、10元、20元等您想捐的金額吧,狠狠點擊下面給點支持吧,站長非常感激您!手機微信長按不能支付解決辦法:請將微信支付二維碼保存到相冊,切換到微信,然后點擊微信右上角掃一掃功能,選擇支付二維碼完成支付。
【本文對您有幫助就好】元
