我正在尝试编写一个递归CTE,以便为所有其他客户提供“主要客户”,但是我不知道从哪里开始。
我已经创建了示例数据集和表结构:
create table T_CUSTOMER_RELATIONSHIP (CUST_ID VARCHAR2(10), OTHER_CUST_ID VARCHAR2(10))
insert into T_CUSTOMER_RELATIONSHIP values ('CUST1', 'CUST1');
insert into T_CUSTOMER_RELATIONSHIP values ('CUST1', 'CUST2');
insert into T_CUSTOMER_RELATIONSHIP values ('CUST1', 'CUST3');
insert into T_CUSTOMER_RELATIONSHIP values ('CUST1', 'CUST4');
insert into T_CUSTOMER_RELATIONSHIP values ('CUST5', 'CUST5');
insert into T_CUSTOMER_RELATIONSHIP values ('CUST5', 'CUST4');
insert into T_CUSTOMER_RELATIONSHIP values ('CUST5', 'CUST6');
insert into T_CUSTOMER_RELATIONSHIP values ('CUST7', 'CUST7');
insert into T_CUSTOMER_RELATIONSHIP values ('CUST7', 'CUST6');
insert into T_CUSTOMER_RELATIONSHIP values ('CUST8', 'CUST8');
insert into T_CUSTOMER_RELATIONSHIP values ('CUST8', 'CUST9');
insert into T_CUSTOMER_RELATIONSHIP values ('CUST8', 'CUST10');
commit;
““主要”客户记录具有相同的CUST_ID和OTHER_CUST_ID值(因此... CUST_ID1,CUST_ID5,CUST_ID7,CUST_ID8是“主要”客户)
我想按如下方式获得(例如)CUST_ID1的结果集:
CUST_ID OTHER_CUST_ID
CUST1 CUST2
CUST1 CUST3
CUST1 CUST4
CUST1 CUST5
CUST1 CUST6
CUST1 CUST7
...这将允许我设置一个提取脚本,该脚本将直接或通过与另一主要客户(及其相关客户,因此与之建立共同关系)为与CUST1相关的所有客户提取所有详细信息。递归)
这可能吗?
您可以使用分层查询:
SELECT DISTINCT
CONNECT_BY_ROOT( cust_id ) AS cust_id,
other_cust_id
FROM T_CUSTOMER_RELATIONSHIP
START WITH cust_id = 'CUST1'
CONNECT BY NOCYCLE
( PRIOR other_cust_id IN ( cust_id, other_cust_id )
OR PRIOR cust_id IN ( cust_id, other_cust_id ) )
ORDER BY cust_id, other_cust_id;
输出:
CUST_ID | OTHER_CUST_ID:------ | :------------CUST1 |客户1CUST1 |客户2CUST1 |客户3CUST1 |客户4CUST1 |客户5CUST1 |客户6CUST1 |客户7
db <>小提琴here