Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL ORDER BY route information

Tags:

sql

mysql

Ik have a table with route information in random order, like this:

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

I'm trying to find a method to sort it using the route information, where the to column of the current row matches with the from column of the next row. In the example, the order I want is:

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

A simple ORDER BY on the from or to column doesn't work because a numerical order isn't the right one. I'm trying to find a method using SQL or Excel.

SQL Fiddle here: http://sqlfiddle.com/#!2/9ebbb

like image 914
Otto Coster Avatar asked Nov 21 '12 09:11

Otto Coster


People also ask

How do you use ORDER BY clause with SQL statement?

The SQL ORDER BY KeywordThe ORDER BY keyword is used to sort the result-set in ascending or descending order. The ORDER BY keyword sorts the records in ascending order by default. To sort the records in descending order, use the DESC keyword.

How do you get query results in the same order as given in clause?

in php u can do it like : <? php $my_array = array (3,6,1,8,9) ; $sql = 'SELECT * FROM table WHERE id IN (3,6,1,8,9)'; $sql .

How do I use both ascending and descending in SQL?

The ORDER BY statement in SQL is used to sort the fetched data in either ascending or descending according to one or more columns. By default ORDER BY sorts the data in ascending order. We can use the keyword DESC to sort the data in descending order and the keyword ASC to sort in ascending order.


2 Answers

This works in oracle

select a.*
from route  a
start with a.rowid = (select min(rowid) from route )
connect by prior a.t = a.f; 
like image 173
Ajith Sasidharan Avatar answered Oct 04 '22 03:10

Ajith Sasidharan


SQL Server (2005+) it will be

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

like image 40
Niladri Biswas Avatar answered Oct 04 '22 05:10

Niladri Biswas