给定航班数据库,找到每个出发城市最长飞行时间的目的地

时间:2017-04-19 03:19:06

标签: sql sqlite azure-sql-database

给出Flight表:

Flights (
    fid, 
    year, 
    month_id, 
    day_of_month, 
    day_of_week_id, 
    carrier_id, 
    flight_num, 
    origin_city, 
    origin_state,
    dest_city,
    dest_state, 
    departure_delay, 
    taxi_out,
    arrival_delay,
    canceled, 
    actual_time, 
    distance
)

我需要为每个城市找到最长飞行时间的目的地。

我在使用子查询时遇到了困难。

我的尝试:

SELECT DISTINCT origin_city, dest_city, MAX(actual_time) 
GROUP BY origin_city

但我知道这是错的。任何指导表示赞赏

2 个答案:

答案 0 :(得分:0)

这将生成一个原始城市列表,目的地城市的飞行时间最长。

编辑 GROUP BY 添加到主查询,按/限制添加到子查询以消除重复的origin_cities。

SELECT
    f.`origin_city`,
    f.`origin_state`,
    f.`dest_city`,
    f.`desc_state`,
    f.`actual_time`
FROM (
    SELECT 
        `origin_city`,
        `origin_state`,
        max(`actual_time`) as `max_time` 
    FROM `Flights` 
    GROUP BY `origin_city`,`origin_state` 
    ORDER BY `max_time` DESC) a
JOIN `Flights` f
ON f.`origin_city` = a.`origin_city`
    AND f.`origin_state` = a.`origin_state`
    AND f.`actual_time` = a.`max_time`
GROUP BY f.`origin_city`,f.`origin_state`

答案 1 :(得分:-1)

$sql = "SELECT MAX(actual_time) FROM FLIGHTS WHERE origin_city=xxxxx";
$result = $conn->query($sql);


while($row = $result->fetch_assoc()) {
    echo  $row["dest_city"];
 }

将上述代码包装在一个循环中,因为每个原始城市都需要目的地城市。