如何基于另一个表的PK获取一个表的两列的计数?

时间:2019-02-17 17:41:52

标签: mysql sql

我有两个表定义为:

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很陌生,不知道如何写。

4 个答案:

答案 0 :(得分:1)

最简单的方法是横向联接和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;

请注意,JOINairports是不必要的,除非您实际上想带来问题中没有提到的更多信息。

答案 1 :(得分:0)

您可以将两个查询用作子查询并加入

    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 ;

答案 2 :(得分:0)

我认为别名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;

答案 3 :(得分:0)

一种非常简单的方法就是在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;