+ -
当前位置:首页 → 问答吧 → A--B--C--D请问高手路由选择怎么做

A--B--C--D请问高手路由选择怎么做

时间:2011-12-20

来源:互联网

有一张表
站点1 站点2
  A B
  B C
  C D
  B E
  E D
查询时提供A,D两点怎么出来路径?
A-B-C-D
A-B-E-D

作者: bolome   发布时间: 2011-12-20

SQL code
--> --> (Roy)生成測試數據
 
if not object_id('Tempdb..#T') is null
    drop table #T
Go
Create table #T([站点1] nvarchar(1),[站点2] nvarchar(1))
Insert #T
select N'A',N'B' union all
select N'B',N'C' union all
select N'C',N'D' union all
select N'B',N'E' union all
select N'E',N'D'
Go
;with b
as
(
Select *,[站点1]+'-'+[站点2] as stop,Path=cast([站点1]+'-'+[站点2] as nvarchar(1000))from #T as a where not exists(select 1 from #T where a.[站点2]=[站点1])
union all
select a.*,b.stop,Path=cast(a.[站点1]+'-'+b.Path as nvarchar(1000)) from #T as a inner join  b on a.[站点2]=b.站点1
)
select a.Path 
from b as a 
where not exists(select 1 from b where Path<a.Path and stop =a.stop)
/*
A-B-E-D
A-B-C-D
*/

作者: roy_88   发布时间: 2011-12-20

作者: roy_88   发布时间: 2011-12-20

十分感谢!好好研读。

作者: bolome   发布时间: 2011-12-20