兩列資料,分別表示火車出發城市和到達城市。每行都表示有路線直達。現在要從蘭州出發到北京,需要找出有一次中轉的,比如 蘭州---西安--北京。這個該怎么解決呢?多謝指點
欄位名 a b
蘭州 北京
西安 重慶
西安 北京
蘭州 西安
uj5u.com熱心網友回復:
if object_id('tempdb..#tab') is not null drop table #tab
create table #tab (s nvarchar(max),e nvarchar(max))
insert into #tab (s,e)
select '蘭州','北京' union all select '西安','重慶' union all
select '西安','北京' union all select '蘭州','西安' union all
select '蘭州','鄭州' union all select '西安','鄭州' union all
select '鄭州','北京' union all select '北京','天津'
select * from #tab
;with t as(
select s,e,0 as lv,s+'---'+e as [path] from #tab where s='蘭州'
union all
select t.s,#tab.e,t.lv+1 as lv ,t.path +'---'+#tab.e from #tab inner join t on t.e=#tab.s
)
select * from t order by lv

結果集中s:始發站;e:終點站;lv:換乘次數. 想要什么結果再加where條件過濾。
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/74756.html
標籤:應用實例
上一篇:入門太難
下一篇:求一款免費的局域網個人磁盤軟體
