我是一名业余爱好者,只是试图完成他的任务的最后一个问题(现在已经过期了,只是寻求理解)我坐了两天,然后开了近5个小时的尝试,并且已经有了没有成功。
我已经尝试查看所有不同类型的连接,无法分组工作(永远)并且也没有运气排序。我可以一次完成所有这些事情,但这里的困难在于让所有这些事情都能在工会中发挥作用。
这就是问题:
编写SQL查询以检索具有(源城市,源代码,目标城市, 所有具有至少2个航班的源 - 目标对的目的地代码和航班号。订购 通过number_of_flights。请注意“flight”表中的“dest”和“source”属性 都引用了“机场”表中的“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
);
我遇到的第一个问题是在同一个查询中输出两次airport.city但结果不同。不仅如此,无论我在分组时尝试了什么,我都会得到相同的结果:
不是GROUP BY表达式
通常我很乐意尝试将这些拼凑在一起,但这令人沮丧。救命啊!
答案 0 :(得分: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;
答案 1 :(得分: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