SQL ORDER BY路由信息

时间:2012-11-21 09:39:22

标签: mysql sql

我有一张包含随机顺序的路线信息的表格,如下所示:

from    to      street
----------------------------------
92      91      Lange Poten
100     104     Bagijnestraat
85      79      Korte Poten
91      85      Plein
79      100     Bezuidenhoutseweg

我正在尝试使用路径信息找到一种方法对其进行排序,其中当前行的列与下一行的列匹配。在示例中,我想要的顺序是:

from    to      street
----------------------------------
92      91      Lange Poten
91      85      Plein
85      79      Korte Poten
79      100     Bezuidenhoutseweg
100     104     Bagijnestraat

列的简单ORDER BY不起作用,因为数字顺序不正确。我正在尝试使用SQL或Excel找到一种方法。

SQL小提琴:http://sqlfiddle.com/#!2/9ebbb

2 个答案:

答案 0 :(得分:8)

这适用于oracle

select a.*
from route  a
start with a.rowid = (select min(rowid) from route )
connect by prior a.t = a.f; 

答案 1 :(得分:5)

SQL Server(2005+)它将是

Declare @Routes Table([from] int, [to] int, [street] varchar(17))   
INSERT INTO @Routes VALUES
(92, 91, 'Lange Poten'),
(100, 104, 'Bagijnestraat'),
(85, 79, 'Korte Poten'),
(91, 85, 'Plein'),
(79, 100, 'Bezuidenhoutseweg')

;With  Cte AS
(
    SELECT  [from]
            ,[to]
            ,[street]
    FROM    @Routes
    WHERE   [from] = 92
    UNION ALL
    SELECT  r.[from]
            ,r.[to]
            ,r. [street]
FROM    @Routes AS r
JOIN    Cte c
ON      c.[to] = r.[from]
)

Select * From Cte

enter image description here