2013-04-04 43 views
0

我有一个ID和位置列的表,我试图将多个行组合成逗号分隔列出。 对于如:Oracle 11g r2字符串汇总

Source table: ID Location  Name 
       1  USA  Bob 
       1  Brazil Bob 
       1  Russia Bob 
       2  India  Emily 
       2  China  Emily 

我的目标表应该得到这样的

Target table: ID Location    Name 
       1  USA, Brail, Russia Bob 
       2  India, China  Emily 

我如何执行此使用Oracle 11g R2的值?

回答

1

您可以使用listagg()

select id, listagg(location, ', ') within group (order by id) as location 
from source 
group by id 

这并不能保证在表中的原始顺序。 SQL表本质上是无序的,所以为了保证这一点,你需要为每一行分配一个不同的行ID。这可能如下亲近:

select id, listagg(location, ', ') within group (order by seqnum) as location 
from (select *, rownum as seqnum from source) s 
group by id 
+0

关键字 – user1751356 2013-04-04 17:36:40

+0

内缺少我想这个选择ID,wm_concat(地点),如ID地址 从sourceTable会 组,这似乎是工作。 – user1751356 2013-04-04 17:49:11

+0

但是,如果我需要从源选择额外的列,我的解决方案无法正常工作。 – user1751356 2013-04-04 17:58:34