0

我是一个业余爱好者,正试图完成他作业的最后一个问题(此时已过期,只是为了寻求理解)我在两天内坐下来尝试了近 5 个小时,但没有成功。

我已经尝试过查看所有不同类型的连接,(永远)无法进行分组工作,并且在排序方面也没有运气。我可以一次做所有这些事情,但这里的困难是让所有这些事情协同工作。

这是问题:

编写一个 SQL 查询以检索包含(源城市、源代码、目的地城市、目的地代码和航班数量)的列表,其中包含至少 2 个航班的所有源-目的地对。按 number_of_flights 排序。请注意,“flights”表中的“dest”和“source”属性都引用了“airports”表中的“airportid”。

这是我必须使用的表(还附带了大约 3000 行虚拟条目)

create table airports (
    airportid char(3)       primary key, 
    city varchar(20)
);
create table airlines (
    airlineid char(2)       primary key, 
    name varchar(20), 
    hub char(3)             references airports(airportid)
); 
create table customers (
    customerid char(10)     primary key, 
    name varchar(25), 
    birthdate date, 
    frequentflieron char(2) references airlines(airlineid)
);
create table flights (
    flightid char(6)        primary key, 
    source char(3)          references airports(airportid), 
    dest char(3)            references airports(airportid), 
    airlineid char(2)       references airlines(airlineid), 
    local_departing_time date, 
    local_arrival_time date
);
create table flown (
    flightid char(6)        references flights(flightid), 
    customerid char(10)     references customers, 
    flightdate date
);

我遇到的第一个问题是在同一个查询中输出 airports.city 两次,但结果不同。不仅如此,无论我在分组时尝试了什么,我总是会得到相同的结果:

不是 GROUP BY 表达式

通常我很乐意尝试将这些拼凑在一起,但这令人沮丧。帮助!

4

2 回答 2

5
select source.airportid as source_airportid,
       source.city source_city,
       dest.airportid as dest_airportid,
       dest.city as dest_city,
       count(*) as flights
from   flights
inner join airports source on source.airportid = flights.source
inner join airports dest on dest.airportid = flights.dest
group by
       source.airportid,
       source.city,
       dest.airportid,
       dest.city
having count(*) >= 2
order by 5;
于 2012-04-17T20:39:40.190 回答
4

您是否尝试过子查询?

SELECT  source_airports.city, 
        source_airports.airportid,
        dest_airports.city,
        dest_airports.airportid,
        x.number_of_flights
FROM 
    (
        SELECT  source, dest, COUNT(*) as number_of_flights
        FROM    flights 
        GROUP BY source, dest
        HAVING COUNT(*) > 1
    ) as x
    INNER JOIN airports as dest_airports
    ON dest_airports.airportid = x.dest
    INNER JOIN airports as source_airports
    ON source_airports.airportid = x.source
ORDER BY x.number_of_flights ASC
于 2012-04-17T20:42:31.903 回答