【问题标题】:How to find frequency of a value in two different columns in sql?如何在sql中的两个不同列中查找值的频率?
【发布时间】:2020-02-09 18:03:26
【问题描述】:

我有一张显示航班到达机场和出发机场的表格。 我需要找到每个机场的到达和离开

First one is the given table and second is the required table

我已经尝试了以下

SELECT T.departure, count(F.departure), count(F.arrival) 
FROM (
    SELECT departure FROM flights 
    UNION 
    SELECT arrival FROM flights
) T
LEFT JOIN flights F ON T.departure  = F.departure
LEFT JOIN flights F2 ON T.departure = F.arrival
GROUP BY T.departure

【问题讨论】:

    标签: mysql oracle database-management


    【解决方案1】:

    这是一种选择:

    SQL> with
      2  test (dep, arr) as
      3    -- your sample data
      4    (select 'a', 'e' from dual union all
      5     select 'a', 'e' from dual union all
      6     select 'a', 'e' from dual union all
      7     select 'b', 'f' from dual union all
      8     select 'b', 'f' from dual union all
      9     select 'b', 'g' from dual union all
     10     select 'c', 'g' from dual
     11    ),
     12  deparr as
     13    -- departures and arrivals
     14    (select dep airport, 1 departure, 0 arrival from test
     15     union all
     16     select arr airport, 0 departure, 1 arrival from test
     17    )
     18  select airport, sum(departure) departure, sum(arrival) arrival
     19  from deparr
     20  group by airport
     21  order by airport;
    
    A  DEPARTURE    ARRIVAL
    - ---------- ----------
    a          3          0
    b          3          0
    c          1          0
    e          0          3
    f          0          2
    g          0          2
    
    6 rows selected.
    
    SQL>
    

    (顺便说一句,您的预期输出似乎是错误的。B 有 3 个出发点。)

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-09-16
      • 1970-01-01
      • 2021-12-30
      • 2020-11-12
      • 1970-01-01
      相关资源
      最近更新 更多