首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 数据库 > SQL Server >

hjywyj 请进,帮小弟我看一上

2013-01-11 
hjywyj 请进,帮我看一下前两天,您回答了我一个问题http://bbs.csdn.net/topics/390334371?page1我做了一

hjywyj 请进,帮我看一下
前两天,您回答了我一个问题
http://bbs.csdn.net/topics/390334371?page=1
我做了一些修改

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 '大连','沈阳','哈大'
),
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()),名称,目的地 from(
select 目的地,名称 from source union all
select 起点,名称 from(
select *,row=row_number()over(order by getdate()) from source)t where row=(select max(row) from (select *,row=row_number()over(order by getdate()) from source)tt)
)ttt


可是我现在想得到以下结果
id名称目的地
1哈大哈尔滨
2哈大沈阳
3哈大大连
4哈深哈尔滨
5哈深北京
6哈深上海
7哈深广州
8哈深深圳

或者
id名称途经
1哈大哈尔滨-沈阳-大连
2哈深哈尔滨-北京-上海-广州-深圳

自己实在搞不定,请高手帮我看看,怎样实现这个结果,万分感谢!!
[解决办法]
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 '大连','沈阳','哈大'
),
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 名称

热点排行