I have this table:
and I was trying to solve this problem given like this:
Give a single SQL query that returns the cheapest cost of flying between each pair of cities assuming we are willing to stop up to two times en route. For example, by stopping once (in Denver), we can get from SF to NY for 700 instead of 750. In this example, we could stop twice (in Denver and Chicago), but that would be more expensive (300 + 250 + 250 = 800)."
In this handout for question number 4b.
I just want it to display for only one en-route stop.
I have so far this query:
SELECT f1.fromCity, f2.toCity as destination, f1.toCity as scale, (MIN(f1.fare) + MIN(f2.fare)) as price
FROM flightfares f1, flightfares f2
WHERE f2.fromCity = f1.toCity
AND f1.fromCity != f2.toCity
GROUP BY f1.fromCity, f1.toCity, f2.toCity
HAVING MIN(f1.fare) AND MIN(f2.fare);
it displays the data from one city to another with 1 stop and the total price.
I am not sure what to do from there on to solve the problem. Can someone provide me with ideas or the solution?
EDIT: Join version?
SELECT f1.fromCity, f2.toCity as destination, f1.toCity as scale, (min(f1.fare) + min(f2.fare)) as price
FROM flighfares f1
JOIN flighfares f2 ON(f2.fromCity = f1.toCity AND f1.fromCity != f2.toCity)
GROUP BY f1.fromCity, f1.toCity, f2.toCity
HAVING min(f1.fare) AND min(f2.fare);