Tim Hall 列出了Oracle 中可用的各种字符串聚合技术的规范列表。
使用连接来组合数据既不实用也不高效。如果您碰巧知道这EntityID
将映射到其他三个Group_EntityID
值,则可以使用连接
SELECT a.entity_id,
a.entity_id || ',' ||
a.group_entityID || ',' ||
b.group_entityID || ',' ||
c.group_entityID
FROM table_name a,
table_name b,
table_name c
WHERE a.entityID = b.entityID
AND a.entityID = c.entityID
AND a.group_entityID > b.group_entityID
AND b.group_entityID > c.group_entityID
Group_EntityID
但是,如果与特定的值相关的数量发生变化,这种方法既不是特别有效也不是特别灵活EntityID
。
我通常更喜欢创建用户定义的聚合函数(蒂姆列表中的选项之一)并执行类似的操作
SELECT entityID, entityID || ',' || string_agg( group_entity_id )
FROM table_name
GROUP BY entityID;
如果您想在不创建任何其他对象或函数的情况下执行此操作,可以使用SYS_CONNECT_BY_PATH
Tim 网站上的方法
SQL> ed
Wrote file afiedt.buf
1 with x as (
2 select 1 group_id, 'A997' entityID, 'A995' group_entityID from dual union all
3 select 2, 'A997', 'A993' from dual union all
4 select 3, 'A997', 'A990' from dual union all
5 select 4, 'A998', 'A987' from dual union all
6 select 5, 'A998', 'A982' from dual union all
7 select 6, 'A998', 'A980' from dual union all
8 select 7, 'A979', 'A975' from dual union all
9 select 8, 'A979', 'A974' from dual union all
10 select 9, 'A979', 'A973' from dual
11 )
12 select entityID,
13 entityID || ',' ||
14 ltrim( max( sys_connect_by_path( group_entityID, ','))
15 keep(dense_rank last order by group_id),
16 ',') group_entityID
17 from (select group_id,
18 entityID,
19 group_entityID,
20 row_number() over (partition by entityID
21 order by group_id) curr,
22 row_number() over (partition by entityID
23 order by group_id) - 1 prev
24 from x)
25 group by entityID
26 connect by prev = PRIOR curr
27 and entityID = PRIOR entityID
28* start with curr = 1
SQL> /
ENTI GROUP_ENTITYID
---- ------------------------------
A979 A979,A975,A974,A973
A997 A997,A995,A993,A990
A998 A998,A987,A982,A980