日期:2014-05-17 浏览次数:20501 次
with table1(起点,目的地,名称) as(
select '广州','深圳','哈深' union all
select '北京','哈尔滨','哈深' union all
select '北京','上海','哈深' union all
select '广州','上海' ,'哈深'union all
select '上海','广州','哈深' union all
select '沈阳','大连','哈大' union all
select '哈尔滨','沈阳','哈大' union all
select '上海','北京','哈深' union all
select '沈阳','哈尔滨','哈大' union all
select '大连','沈阳','哈大'union all
select '哈尔滨','长春','京哈'union all
select '长春','哈尔滨','京哈'union all
select '长春','沈阳','京哈'union all
select '沈阳','长春','京哈'union all
select '沈阳','北京','京哈'union all
select '沈阳','北京','京哈'union all
select '兰州','张掖','兰新'union all
select '张掖','兰州','兰新'union all
select '张掖','乌鲁木齐','兰新'union all
select '乌鲁木齐','张掖','兰新'
),
tb as(
select 起点,目的地,名称 from(
select *,row=row_number()over(partition by 起点,目的地 order by getdate())from(
select * from table1 union all
select 目的地,起点,名称 from table1)t
)tt where row=1
),
tbfirst as ( select top 1 起点,COUNT(起点) as shuliang from tb group by 起点
having COUNT(起点)=1),
source as(
select * from tb where 目的地=(select 起点 from tbfirst)
union all
select tb1.* from tb tb1,source s1 where tb1.目的地=s1.起点 and tb1.起点!=s1.目的地
)
select id=row_number()over(order by getdate()),名称,(select top 1 起点 from source s2 where s2.名称=s1.名称)+(select '-'+目的地 from source s2 where s2.名称=s1.名称 for xml path('')) 途经 from source s1 group by 名称