Skip to content

Instantly share code, notes, and snippets.

@IAMakarov
Created June 4, 2025 16:12
Show Gist options
  • Select an option

  • Save IAMakarov/ade78466445b73598c00ba92799b519c to your computer and use it in GitHub Desktop.

Select an option

Save IAMakarov/ade78466445b73598c00ba92799b519c to your computer and use it in GitHub Desktop.
Query Exercise: Return Routes in the Right Order
with t as
(
select
stationName s,
stationPhysicalOrder o,
lead(stationName) over (order by stationPhysicalOrder) ns,
min(stationPhysicalOrder) over () mino
from
dbo.Stations
),
r as
(
select cast(1 as int) o, s from t where o = mino
union all
select
r.o + 1, isnull(so.ns, t.ns)
from
r
outer apply (select StationToName from dbo.StationRoutingOverride where StationFromName = r.s) so (ns)
join t on r.s = t.s
)
select s from r
where s is not null
order by o
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment