我在DB2中创建了一个表:
CREATE TABLE mytable
(
loan_id integer,
client_id integer
);
将值插入表中:
INSERT INTO mytable(
loan_id, client_id)
VALUES (1, '2');
最后,该表包含以下数据:
loan_id client_id
1 2
1 4
4 2
2 3
我想运行一个SQL查询,它将枚举(打印)所有唯一可能的路径。下面给出了一个示例输出:
1 -> 2
1 -> 4
4 -> 2
2 -> 3
1 -> 2 -> 3
4 -> 1 -> 2
4 -> 2 -> 3
4 -> 1 -> 2 -> 3
3 -> 2 -> 4 -> 1
我查看了以下answer并尝试了以下代码,它给出了错误:
WITH links AS
( SELECT
loan_id,
client_id as c1,
client_id as c2, 0 as distance
FROM
mytable
-- recursion
UNION ALL
SELECT
t.loan_id,
l.c1 as c1,
tt.client_id as c2,
distance+ as distance
FROM
links l INNER JOIN
myTable t ON l.c2 = t.client_id
AND l.loan_id != t.loan_id INNER JOIN
myTable tt ON t.loan_id = tt.loan_id
AND t.client_id != tt.client_id
)
SELECT * FROM mytable t
WHERE EXISTS
(SELECT * FROM links
WHERE c2 = t.client_id and c1 = 3);
感谢您的帮助。
答案 0 :(得分:0)
您可以在SYS_CONNECT_BY_PATH函数中搜索
答案 1 :(得分:0)
在SQL SERVER VERSION中:
WITH allvalue as (
select loan_id id from mytable
union
select client_id id from mytable
),
allvaluewithnbcombi as (
select f1.*, (select count(*) from allvalue f2) nbcombi from allvalue f1
)
,
tmprecurse (id, pathcalcul, rang, nbcombi) as (
select id , cast('' as varchar(50)) as pathcalcul, 1 rang, nbcombi from allvaluewithnbcombi
union all
select f1.id , cast(case when pathcalcul='' then cast(f2.id as varchar(50)) else f2.pathcalcul + '->' + cast(f2.id as varchar(50)) end as varchar(50)) pathcalcul,
f2.rang + 1, f1.nbcombi
from allvaluewithnbcombi f1, tmprecurse f2
where f1.id<>f2.id and f2.rang<=f1.nbcombi
)
, resultat as (
select distinct pathcalcul from tmprecurse
where pathcalcul<>'' and pathcalcul like '%->%'
)
select * from resultat
order by len(pathcalcul)
在DB2 VERSION中(未测试)
WITH allvalue as (
select loan_id id from mytable
union
select client_id id from mytable
),
allvaluewithnbcombi as (
select f1.*, (select count(*) from allvalue f2) nbcombi from allvalue f1
)
,
tmprecurse (id, pathcalcul, rang, nbcombi) as (
select id , cast('' as varchar(50)) as pathcalcul, 1 rang, nbcombi from allvaluewithnbcombi
union all
select f1.id , cast(case when pathcalcul='' then cast(f2.id as varchar(50)) else f2.pathcalcul concat '->' concat cast(f2.id as varchar(50)) end as varchar(50)) pathcalcul,
f2.rang + 1, f1.nbcombi
from allvaluewithnbcombi f1, tmprecurse f2
where f1.id<>f2.id and f2.rang<=f1.nbcombi
)
, resultat as (
select distinct pathcalcul from tmprecurse
where pathcalcul<>'' and pathcalcul like '%->%'
)
select * from resultat
order by len(pathcalcul)
我希望你这是对的