这篇文章主要讲解了“SQL行转列合并的语句”,文中的讲解内容简单清晰,易于学习与理解,下面请大家跟着小编的思路慢慢深入,一起来研究和学习“SQL行转列合并的语句”吧!
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
感谢各位的阅读,以上就是“SQL行转列合并的语句”的内容了,经过本文的学习后,相信大家对SQL行转列合并的语句这一问题有了更深刻的体会,具体使用情况还需要大家实践验证。这里是亿速云,小编将为大家推送更多相关知识点的文章,欢迎关注!