I made a few assumptions. First, the routes only go in one direction, ie, A->B->C->D. Second, truck numbers are unique and don't skip numbers. Third, origins and destinations are always alphabetical.
So, step one was to create a table with all of the possible origin/destination permutations. That was done with the Cross Join and a While loop to iterate through the trucks/origins/destinations. As the same time, I calculated the transit time between each permutation.
Next would be the X number of stops. That's where the Row_Number comes in. Partitioned and ordered the way it is, you can simply select everything less than or equal to your X number of stops (@Destinations). If you set @Destinations to a number greater than what's in the ResultsTable, it will just return the whole table. If you set it to 0 or NULL, it returns nothing.
Finally, in your expected results, you have two different calculations for Transit Time. A>B is 5 days but only if you count both Departure and Arrival. B>C is 5 days but only if you don't count both. I counted both. If you only want to count one, take out the + 1 in the Transit calculation.
Fiddle
DECLARE @Destinations INT = 3
DECLARE @Truck INT = 0
DECLARE @maxTruck INT
DECLARE @ResultTable TABLE
(rn INT, TruckNumber INT, Origin CHAR, Destination CHAR, Transit VARCHAR(10));
SELECT @maxTruck = MAX(TruckNumber)
FROM trips;
WHILE @Truck <= @maxTruck
BEGIN
INSERT INTO @ResultTable (rn, TruckNumber, Origin, Destination, Transit)
SELECT
DISTINCT ROW_NUMBER() OVER (PARTITION BY t1.TruckNumber, t1.origin ORDER BY t1.origin, t2.Destination) AS rn,
t1.TruckNumber,
t1.Origin,
t2.Destination,
DATEDIFF(DAY, t1.departure, t2.Arrival )+ 1 AS Transit
FROM trips t1
CROSS JOIN trips t2
WHERE t2.destination > t1.origin
AND t1.TruckNumber = @Truck and t2.TruckNumber = @Truck
SET @Truck = @Truck + 1
END
SELECT --rn,
TruckNumber,
Origin,
Destination,
CONCAT(Transit, ' Days') Transit
FROM @ResultTable
WHERE rn <= @Destinations
ORDER BY TruckNumber,Origin,Destination
@Destinations = 3 returns:
TruckNumber |
Origin |
Destination |
Transit |
1 |
A |
B |
5 Days |
1 |
A |
C |
15 Days |
1 |
A |
D |
20 Days |
1 |
B |
C |
6 Days |
1 |
B |
D |
11 Days |
1 |
B |
E |
13 Days |
1 |
C |
D |
5 Days |
1 |
C |
E |
7 Days |
1 |
D |
E |
3 Days |
2 |
A |
B |
11 Days |