【发布时间】:2019-07-11 03:56:36
【问题描述】:
我有两个表定义为:
CREATE TABLE airports (
code char(3) not null primary key,
name varchar(100) not null,
city varchar(50) not null,
state varchar(5),
country char(2) not null references fcountries(code)
)
和
CREATE TABLE flights (
departure char(3) not null references airports(code), -- airport code
arrival char(3) not null references airports(code), -- airport code
dep_time time not null,
airline char(2) not null references airlines(code)
)
我需要使用 postgres 获取从机场出发和到达机场的航班数量。所以,我写了
select
code,
count(departure)
from airports
join flights
on flights.departure = airports.code group by code;
对于出发也是如此,
select
code,
count(arrival) as Arrival
from airports
join flights
on flights.arrival = airports.code group by code;
但我需要将这两者结合起来,并在相同的结果中获得到达-离开计数。我不知道该怎么做? 我写了这个查询
select
code,
count(departure),
x.arrival
from (
select count(arrival) as arrival
from airports
join flights
on flights.arrival = airports.code group by code
) x,
airports
join flights on airports.code = flights.departure
group by code, x.arrival
order by code;
但结果不正确,因为在此结果中重复了“代码”。我对 sql 很陌生,不知道怎么写。
【问题讨论】:
-
更新您的问题,添加相关表架构一个适当的数据样本和预期结果
-
请决定 DBMS。
-
我猜错了。
group by code而不是roup by code -
我改了还是有错误。