gpt4 book ai didi

sql - 同一张表上两个不同聚合函数的连接结果

转载 作者:行者123 更新时间:2023-12-04 14:04:53 27 4
gpt4 key购买 nike

我试图结合两个查询,以确定哪架飞机将在特定时间 (2011-09-19 04:00:00.000) 之前的特定点(点 ABCD)。到目前为止,我生成了最后一次飞机到达该点的时间,以及最后一次飞机离开该点的时间。我目前的想法是,如果最后一次到达的时间大于最后一次离开的时间,那么飞机仍然在指定时间之前的 ABCD 点。

第一个查询查找飞机最后一次到达某个点的时间:

select aircraft_id, MAX(arrival_datetime) as last_arrival
from flight_schedule
where arrival_datetime < '2011-09-19 04:00:00.000' and arrival_point='ABCD'
group by aircraft_id

第二个查询查找飞机最后一次离开该点的时间:
select aircraft_id, MAX(departure_datetime) as last_departure
from flight_schedule
where departure_datetime < '2011-09-19 04:00:00.000' and departure_point='ABCD'
group by aircraft_id

这两个查询都会生成适当的响应。我意识到为了将 last_departure 与 last_arrival 字段进行比较,我需要以某种方式加入表格。

我不是 SQL 高手,过去我所做的任何表连接都是在两个完全不同的表之间进行的,并且没有涉及任何聚合函数,因此我的正常子查询和结构不起作用。

最佳答案

最简单的解决方案是

  • 将每个语句变成子查询
  • 将结果连接在一起

  • SQL语句
    select la.aircraft_id, la.last_arrival, ld.last_departure
    from (
    select aircraft_id, MAX(arrival_datetime) as last_arrival
    from flight_schedule
    where arrival_datetime < '2011-09-19 04:00:00.000' and arrival_point='ABCD'
    group by aircraft_id
    ) la
    full outer join (
    select aircraft_id, MAX(departure_datetime) as last_departure
    from flight_schedule
    where departure_datetime < '2011-09-19 04:00:00.000' and departure_point='ABCD'
    group by aircraft_id
    ) ld on ld.aircraft_id = la.aircraft_id

    请注意,我使用了 full outer join .很可能是 inner join就足够了。 full outer join仅当存在 arival_datetime 时才需要没有 departure_datetime反之亦然(这不太可能发生)。

    关于sql - 同一张表上两个不同聚合函数的连接结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7631992/

    27 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com