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
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.
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 .
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.
select a.*
from route a
start with a.rowid = (select min(rowid) from route )
connect by prior a.t = a.f;
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With