我无法弄清楚如何进行oracle查询来执行以下操作:
仅索引端口ID,所有端口左右连接。 在开始时只有PORTID_A编号1是已知的,所以通过简单的查询我找到了PORTID_B。 但港口有时从A开始,有时在B开始。如下所示:
PORTID_A PORTID_B LABEL
1 2 label-01
2 4 label-02
3 4 label-03
6 3 label-04
5 6 label-05
如何获取创建以下内容的查询结果:
1 <-- label-01 --> 2 <-- label-02 --> 4 <-- label-03 --> 3 etc.....
为了从下面的表格中给出一个更好的例子,PORTID_A和PORTID_B被编入索引。
Table: ------------------------------------------------------------------------------------------ PORTID_A PORTID_B PORTLABEL_A PORTLABEL_B 7742140 4298763 00005-ERS10-001/00-0/10-04/1Rx 00005-ODF03-006/06-0/08-0/08 4298763 6853090 00005-ODF03-006/06-0/08-0/08 00005-ODF03-004/02-0/08-0/11 6853497 6853090 00034-ODF03-002/07-0/08-0/11 00005-ODF03-004/02-0/08-0/11 1381299 6853497 00034-ODF03-002/05-0/06-0/03 00034-ODF03-002/07-0/08-0/11 1374115 1381299 00034-ODF03-005/05-0/06-0/03 00034-ODF03-002/05-0/06-0/03 1374115 186966 00034-ODF03-005/05-0/06-0/03 00034-ODF03-005/07-0/04-0/07 24919318 186966 20998-ODF05-002/00-0/01-0/03 00034-ODF03-005/07-0/04-0/07 24919351 24919318 20998-ESU02-001/00-0/00-25/1Tx 20998-ODF05-002/00-0/01-0/03 Result example: ------------------------------------------------------------------------------------------ 00005-ERS10-001/00-0/10-04/1Rx 00005-ODF03-006/06-0/08-0/08 00005-ODF03-004/02-0/08-0/11 00034-ODF03-002/07-0/08-0/11 00034-ODF03-002/05-0/06-0/03 00034-ODF03-005/05-0/06-0/03 00034-ODF03-005/07-0/04-0/07 20998-ODF05-002/00-0/01-0/03 20998-ESU02-001/00-0/00-25/1Tx
答案 0 :(得分:1)
要连接它们,我首先要解决portB可能低于portA的问题:
select
least(PortID_A, PortID_B) as PortID_A,
greatest(PortID_A, PortID_B) as PortID_B,
Label
from
YourTable
之后,您可以通过端口ID连接它们:
select
l.PortID_A,
l.PortID_B,
l.Label
from
ThatQueryFromAbove l
start with
l.PortID_A = 1
connect by
l.PortID_A = prior l.PortID_B;
最后,您可以汇总它以获得结果:
with
VW_LABELS as
(select
least(PortID_A, PortID_B) as PortID_A,
greatest(PortID_A, PortID_B) as PortID_B,
Label
from
YourTable),
VW_CHAINLINKS as
(select
l.PortID_A,
l.PortID_B,
l.Label
from
VW_LABELS l
start with
l.PortID_A = 1
connect by
l.PortID_A = prior l.PortID_B)
select
'1' || LISTAGG (
' <-- ' || c.Label || ' --> ' || c.PortID_B,
''
) WITHIN GROUP (order by c.PortID_A)
from
VW_CHAINLINKS c
当然,您可以将这些步骤结合起来进行更短的查询,但要了解不同的问题,将它们分开可能是一个好主意。 with
语句可以很方便地编写简单的短查询,这些查询可以处理上一个查询的结果。