SQL小技巧系列 --- 行轉列合併

 首先讓咱們來看看這個神奇的函數wm_concat(列名),該函數能夠把列值以","號分隔起來,並顯示成一行,接下來上例子,看看這個神奇的函數如何應用ide

準備測試數據函數

 

SQL> create table test(id number,name varchar2(20));測試

SQL> insert into test values(1,'a');spa

SQL> insert into test values(1,'b');it

SQL> insert into test values(1,'c');table

SQL> insert into test values(2,'d');class

SQL> insert into test values(2,'e');test

 

SQL> commit;擴展

 

效果1 : 行轉列select

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

相關文章
相關標籤/搜索