select x.nr_line as Pierwsza, y.nr_line as druga from Course x, Course y, ( select top 1 A.course_id as startt, B.course_id as endd, A.stop_id, A._time as Atime, B._time as Btime, DATEDIFF(minute, A._time, B._time) as Diff from (select course_id, stop_id, _time from TimeTable where TimeTable.course_id in (select course_id from TimeTable join Stops on TimeTable.stop_id = Stops.stop_id where Stops.stop_name = 'Arkadia') ) A join (select course_id, stop_id, _time from TimeTable where TimeTable.course_id in (select course_id from TimeTable join Stops on TimeTable.stop_id = Stops.stop_id where Stops.stop_name = 'Sadyba') ) B on A.stop_id = B.stop_id AND A.course_id != B.course_id where A._time < B._time order by Diff ) z where x.course_id = z.startt AND y.course_id = z.endd