![](/img/trans.png)
[英]how to get the count of records in one table based on two date fields in another table
[英]How to get count of two columns of a table based on PK of another table?
我有兩個表定義為:
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 很陌生,不知道如何寫這個。
最簡單的方法是橫向連接和group by
:
select v.code, count(*) as total,
sum(is_departure) as num_departures,
sum(is_arrival) as num_arrivals
from flights cross join lateral
(values (departure, 1, 0), (arrival, 0, 1)
) as v(code, is_departure, is_rrival)
on f.departure = a.code
group by v.code;
請注意, JOIN
to airports
是不必要的,除非您確實想引入問題中未提及的更多信息。
您可以將這兩個查詢用作子查詢並加入
select t1.code, t1.count_departure, t2.count_arrival
from (
select code, count(departure) count_departure
from airports join flights on flights.departure = airports.code
group by code
) t1
inner join (
select code, count(arrival) as count_arrival
from airports join flights on flights.arrival = airports.code
roup by code
) t2 on t1.code = t2.code ;
我認為在加入后不能像這樣使用別名 t2 這就是為什么你會收到錯誤。 嘗試這個:
select t1.code, t1.count_departure, t2.count_arrival from ( select code, count(departure) count_departure from airports join flights on flights.departure = airports.code group by code ) t1 join ( select code, count(arrival) as count_arrival from airports join flights on flights.arrival = airports.code group by code ) t2 on t1.code = t2.code;
一個非常簡單的方法是在 SELECT 子句中使用相關的 COUNT 子查詢:
select a.code,
(select count(*) from flights f where f.departure = a.code) as departures,
(select count(*) from flights f where f.arrival = a.code) as arrivals
from airports a;
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.