Skip to content

Instantly share code, notes, and snippets.

@MikeBogdanov
Created June 4, 2025 16:53
Show Gist options
  • Select an option

  • Save MikeBogdanov/5e97f9a4fc6169a7a140714edf21411e to your computer and use it in GitHub Desktop.

Select an option

Save MikeBogdanov/5e97f9a4fc6169a7a140714edf21411e to your computer and use it in GitHub Desktop.
;WITH cte AS
(
SELECT StationName ,
StationPhysicalOrder
FROM Stations
WHERE StationPhysicalOrder = (SELECT MIN(StationPhysicalOrder) FROM Stations)
UNION ALL
SELECT COALESCE(StOverride.StationToName, Stations.StationName) AS StationName ,
COALESCE(StOverride.StationPhysicalOrder, Stations.StationPhysicalOrder) AS StationPhysicalOrder
FROM Stations
JOIN cte
ON Stations.StationPhysicalOrder = cte.StationPhysicalOrder + 1
OUTER APPLY
(
SELECT StationRoutingOverride.StationToName, StationOverride.StationPhysicalOrder
FROM StationRoutingOverride
JOIN Stations AS StationOverride
ON StationOverride.StationName = StationRoutingOverride.StationToName
WHERE StationFromName = cte.StationName
) StOverride
)
SELECT StationName
FROM cte
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment