我想使用JOIN将行转换为oracle 10g中的列。我不想使用DECODE或XMLAGG函数。我的表格结构如下:
GROUP_ID ENTITYID GROUP_ENTITYID
1 A997 A995
2 A997 A993
3 A997 A990
4 A988 A987
5 A988 A982
6 A988 A980
7 A979 A975
8 A979 A974
9 A979 A973
我希望以下列格式获取数据:
ENTITYID GROUP_ENTITYID
A979 A979,A975,A974,A973
A988 A988,A987,A982,A980
A997 A997,A995,A993,A990
你们能告诉我怎么做吗?
提前致谢。
答案 0 :(得分:1)
使用联接来组合数据既不实际也不高效。如果您碰巧知道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
值的数量发生变化,那么该方法既不特别有效,也不具有特别的灵活性。
我通常更喜欢创建用户定义的聚合函数(Tim列表中的一个选项)并执行类似
的操作SELECT entityID, entityID || ',' || string_agg( group_entity_id )
FROM table_name
GROUP BY entityID;
如果您想在不创建任何其他对象或功能的情况下执行此操作,可以在Tim的网站上使用SYS_CONNECT_BY_PATH
方法
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