前两天,您回答了我一个问题
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 哈深 哈尔滨-北京-上海-广州-深圳自己实在搞不定,请高手帮我看看,怎样实现这个结果,万分感谢!!

解决方案 »

  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()),名称,(select top 1 起点 from source s2 where s2.名称=s1.名称)+(select '-'+目的地 from source s2 where s2.名称=s1.名称 for xml path('')) 途经 from source s1 group by 名称
      

  2.   

    找到问题了,最后一句写反了改成
    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 名称 就可以了,再次感谢!