listagg能把非分組列的信息歸並一起,能在分組查詢語句中和count,avg,sum及分組列並列查詢,也算一絕。其基本用法如下:
建表:
create table emp6( id number(8), name nvarchar2(20), vocation nvarchar2(20), primary key(id) )
充值:
insert into emp6(id,name,vocation) values(1,'andy','worker'); insert into emp6(id,name,vocation) values(2,'bill','worker'); insert into emp6(id,name,vocation) values(3,'cindy','worker'); insert into emp6(id,name,vocation) values(4,'douglas','doctor'); insert into emp6(id,name,vocation) values(5,'eliot','doctor'); insert into emp6(id,name,vocation) values(6,'felix','nurse');
現在想按職業分組,有想知道哪個職業有哪些人,listagg函數正好派上用場:
select count(*) as cnt,vocation,listagg(name,',') within group(order by 1) as names from emp6 group by vocation
執行結果:
SQL> select count(*) as cnt,vocation,listagg(name,',') within group(order by 1) as names from emp6 group by vocation ; CNT VOCATION NAMES ---------- -------------------- ---------------------------------------- 2 doctor douglas,eliot 3 worker andy,bill,cindy 1 nurse felix
這是在oracle19c上的效果,沒啥毛病。
但是,在11g上就是這個效果:
SQL> select count(*) as cnt,vocation,listagg(name,',') within group(order by 1) as names from emp6 group by vocation; CNT VOCATION ---------- ---------------------------------------- NAMES ---------------------------------------- 2 doctor d o u g l a s, e l i o t 1 nurse f e l i x 3 worker a n d y, b i l l, c i n d y
而且,出來的結果里的空白字符,用java的Character.isWhiteSpace是區別不出來的,用正則表達式\\s+也沒有用...
要解決也很簡單,用to_char函數將name字段包一下就好了,如下:
select count(*) as cnt,vocation,listagg(to_char(name),',') within group(order by 1) as names from emp6 group by vocation
執行效果:
SQL> select count(*) as cnt,vocation,listagg(to_char(name),',') within group(order by 1) as names from emp6 group by vocation; CNT VOCATION NAMES ---------- -------------------- ---------------------------------------- 2 doctor douglas,eliot 1 nurse felix 3 worker andy,bill,cindy
END