日期:2014-05-17  浏览次数:20394 次

一个简单的表,复杂的查询,求教!
我有一个列车行驶的 起点-目的地表
id 起点 目的地
1 北京 上海
2 北京 哈尔滨
3 广州 深圳
4 广州 上海
5 上海 广州
6 上海 北京

要求得出的表是 途经站表
id 途经(站)
1 哈尔滨
2 北京
3 上海
4 广州
5 深圳

注意:不是简单的distinct,他是按顺序来的 :哈尔滨-北京-上海-广州-深圳
我曾经用若干个临时表实现过,太麻烦,请教高手还有没有其他简单的方法,谢谢

------解决方案--------------------
with table1(id,起点,目的地) as(
select 1,'北京','上海' union all
select 2,'北京','哈尔滨' union all
select 3,'广州','深圳' union all
select 4,'广州','上海' union all
select 5,'上海','广州' union all
select 6,'上海','北京'
),
tb as(
select id,起点,目的地 from(
select *,row=row_number()over(partition by 起点,目的地 order by getdate())from(
select * from table1 union all
select id,目的地,起点 from table1)t
)tt where row=1
),
source as(
select * from tb where 目的地='哈尔滨'
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