日期:2014-05-17 浏览次数:20669 次
--if object_id('train') is not null
-- drop table train
--Go
--Create table train([车次] nvarchar(5),[所在站] nvarchar(2),[站序] smallint)
--Insert into train
--Select N'D3001',N'上海',1
--Union all Select N'D3001',N'苏州',2
--Union all Select N'D3001',N'镇江',5
--Union all Select N'D3001',N'合肥',9
--Union all Select N'Z90',N'上海',1
--Union all Select N'Z90',N'苏州',2
--Union all Select N'G7900',N'上海',1
--Union all Select N'G7900',N'北京',2
--Union all Select N'D1001',N'上海',1
--Union all Select N'D1001',N'合肥',2
DECLARE @Station_Start NVARCHAR(50),@Station_End NVARCHAR(50)
SELECT
@Station_Start=N'上海'
,@Station_End=N'合肥'
--1.
SELECT a.车次 FROM train AS a
WHERE a.所在站=@Station_Start
AND EXISTS(SELECT 1 FROM train AS x
WHERE x.所在站=@Station_End
AND a.车次=x.车次
)
/*
车次
-----
D3001
D1001
*/
--2.
SELECT c.* FROM train AS a
INNER JOIN train AS b ON a.车次=b.车次
INNER JOIN train AS c ON a.车次=c.车次 AND c.站序 BETWEEN a.站序 AND b.站序
WHERE a.所在站=@Station_Start
AND b.所在站=@Station_End
ORDER BY a.车次 ASC,a.站序 ASC
/*
车次 所在站 站序
---------------------
D1001 上海 1
D1001 合肥 2
D3001 上海 1
D3001 苏州 2
D3001 镇江 5
D3001 合肥 9
*/