I have a table with information about flights between cities that looks like this:
origin_city dest_city time
Dothan AL Atlanta GA 171
Dothan AL Elsewhere AL 2
Boston MA New York NY 5
Boston MA City MA 5
New York NY Boston MA 5
New York NY Poughkipsie NY 2
I want to return, for each origin city, the maximum flight time and the destination city or cities that go with it. So the results would look like this:
Dothan AL Atlanta GA 171
Boston MA New York NY 5
Boston MA City MA 5
New York NY Boston MA 5
Based on other threads, like Reason for Column is invalid in the select list because it is not contained in either an aggregate function or the GROUP BY clause, I wrote a query that returns the max flight time from each origin city:
SELECT DISTINCT F.origin_city AS origin_city, Max(F.actual_time) AS actual_time
FROM Flights AS F
GROUP BY F.origin_city
ORDER BY F.origin_city
But I get various errors when I try to include the destination(s) that match that time. For example:
SELECT DISTINCT F.origin_city AS origin_city, Max(F.actual_time) AS actual_time, F.dest_city AS dest_city
FROM Flights AS F
GROUP BY F.origin_city
HAVING
(MAX(F.actual_time) = F.actual_time)
ORDER BY F.origin_city
GO
... gives me the error "Column 'Flights.actual_time' is invalid in the HAVING clause because it is not contained in either an aggregate function or the GROUP BY clause." I tried adding F.actual_time to the group by, but then I get tons of results because I get the max flight time for each origin/destination pair (I think). Also, the actual_time field should be contained in an aggregate function: Max.
This code:
SELECT F.origin_city AS origin_city, Max(F.actual_time) AS actual_time, F.dest_city AS dest_city
FROM Flights as F
WHERE F.actual_time IN (SELECT MAX(actual_time) FROM Flights AS F2 GROUP BY F2.origin_city)
GROUP BY F.origin_city
gives a similar error: Column 'Flights.dest_city' is invalid in the select list because it is not contained in either an aggregate function or the GROUP BY clause.
How can I return all 3 columns correctly?