一个简单的表,复杂的查询,求教!

hzg98 2013-01-01 11:04:59
我有一个列车行驶的 起点-目的地表
id 起点 目的地
1 北京 上海
2 北京 哈尔滨
3 广州 深圳
4 广州 上海
5 上海 广州
6 上海 北京

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

注意:不是简单的distinct,他是按顺序来的 :哈尔滨-北京-上海-广州-深圳
我曾经用若干个临时表实现过,太麻烦,请教高手还有没有其他简单的方法,谢谢
...全文
281 4 打赏 收藏 转发到动态 举报
写回复
用AI写文章
4 条回复
切换为时间正序
请发表友善的回复…
发表回复
hzg98 2013-01-05
  • 打赏
  • 举报
回复
自己改了一下
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
),
 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
hzg98 2013-01-02
  • 打赏
  • 举报
回复
引用 1 楼 hjywyj 的回复:
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,'上海','北京' )……
答案太经典了,刚刚把sqlserver2000 换成sqlserver2008 发现多了好多函数,自己落伍了很多,非常感谢,另外,你给的语句中出现
select * from tb where 目的地='哈尔滨'
能不能再帮我修改一下,因为“哈尔滨”和“深圳”是认为判断的节点,能不能给他换成函数,让程序自己判断路由的起始点或终点,再次感谢!
xuan19950811 2013-01-02
  • 打赏
  • 举报
回复
对对 楼上的这个解法很恰当
  • 打赏
  • 举报
回复
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

34,590

社区成员

发帖
与我相关
我的任务
社区描述
MS-SQL Server相关内容讨论专区
社区管理员
  • 基础类社区
  • 二月十六
  • 卖水果的net
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧