小编典典

查找列值的连通性

sql

我有带有示例数据的下表:

桌子: tbl_nodes

create table tbl_nodes
(
    nod1 varchar(50),
    nod2 varchar(50),
    nod_lenght float
);

样本数据:

insert into tbl_nodes values('A','B',1600); 
insert into tbl_nodes values('G','H',45000);
insert into tbl_nodes values('B','C',2300);
insert into tbl_nodes values('C','D',2640);
insert into tbl_nodes values('B','D',2840);
insert into tbl_nodes values('C','E',2940);
insert into tbl_nodes values('D','F',2340);
insert into tbl_nodes values('M','N',9000);
insert into tbl_nodes values('E','A',100000);

预期结果

Connectivity        Total_Length
----------------------------------
A-B-C-D-F           8880
A-B-C-E-A           106840
A-B-D-F             6780

注意 :我试图找出节点的连通性以及节点之间的长度之和。

我尝试以下查询相同:

我的尝试

;WITH CTE AS
(
    SELECT nod1,nod2 ,sum(nod_lenght) as Total_length
    from tbl_nodes T1
    where EXISTS (select 1 from tbl_nodes T2 where T1.nod2 =T2.nod1) OR 
    EXISTS (select 1 from tbl_nodes T3 WHERE T1.nod1 =T3.nod2)
    GROUP BY nod1,nod2 
)
SELECT STUFF((select '-'+ case when c1.nod2 = c2.nod1 then c1.nod1 else c2.nod2 end
              from CTE c1 
              where c1.nod2 =c2.nod1 or c1.nod1 =c2.nod2
              for xml path('')),1,1,''),Total_length
FROM CTE c2

无法获得预期的结果。


阅读 163

收藏
2021-04-07

共1个答案

小编典典

我很确定您需要递归CTE。但是,您的样本结果没有任何意义。

以下内容基本上可以满足您的要求:

with cte AS (
      select nod1, nod2, nod_length as Total_length,
             convert(varchar(max), concat('-', nod1, '-', nod2, '-')) as nodes, 1 as lev
      from tbl_nodes n
      where nod1 = 'A'
      union all
      select cte.nod1, n.nod2, cte.Total_length + n.nod_length,
             convert(varchar(max), concat(cte.nodes, n.nod2, '-')) as nodes, lev + 1
      from cte join
           tbl_nodes n
           on cte.nod2 = n.nod1
      where nodes not like concat('%-', n.nod2, '-%') 
     )
select nodes, total_length
from cte
where not exists (select 1
                  from cte cte2
                  where cte2.nodes like concat(cte.nodes, '_%')
                 );

是一个db<> fiddle

2021-04-07