mysql 使用sql查找源和最终目标

nhhxz33t  于 2023-01-20  发布在  Mysql
关注(0)|答案(2)|浏览(177)

我有一个表source_flight_destination,如下所示
| 识别号|航班|源|目的地|
| - ------|- ------|- ------|- ------|
| 1个|靛蓝|第二章|BB型|
| 第二章|亚洲航空|AA|第二章|
| 三个|靛蓝|BB型|JJ|
| 四个|香料喷射器|安全等级|BB型|
| 五个|靛蓝|JJ|安全等级|
| 六个|亚洲航空|第二章|KK公司|
| 七|香料喷射器|BB型|JJ|
输出应该是航班、出发地和目的地,如下所示
| 飞行|源|目的地|
| - ------|- ------|- ------|
| 亚洲航空|AA|KK公司|
| 靛蓝|第二章|安全等级|
| 香料喷射机|安全等级|JJ|
我想出了一个可行的解决办法:

with ranked as (
    select *,
    row_number() over (partition by flight order by id asc) as rn
    from source_destination_flight
),
minima as (
    select flight, min(rn) as minrn from ranked group by flight ),
maxima as (
    select flight, max(rn) as maxrn from ranked group by flight),
sourced as (
        select 
              r.flight, 
              r.source as source 
        from ranked r 
        join minima m1 on m1.flight=r.flight and m1.minrn=r.rn
),
destination as (
     select 
           r1.flight, 
           r1.destination as destination 
     from ranked r1 
     join maxima m2 
     on m2.flight=r1.flight and m2.maxrn=r1.rn
)
select
    s.flight, s.source, d.destination from sourced s join destination d on s.flight=d.flight

其目的是:

  • 给予按航班分组的row_number()作为分区,
  • 找出每个分区的row_number的最小值和最大值,
  • 通过基于最小值和最大值进行过滤来选择源和目的地。

然而,这个解决方案看起来彻头彻尾的丑陋,我相信有一个简单得多的解决方案在那里。
有人能给予我指点吗?

wj8zmpe1

wj8zmpe11#

对于此示例数据,可以使用窗口函数FIRST_VALUE()

SELECT DISTINCT Flight,
       FIRST_VALUE(source) OVER (PARTITION BY Flight ORDER BY ID) AS source,
       FIRST_VALUE(destination) OVER (PARTITION BY Flight ORDER BY ID DESC) AS destination
FROM source_destination_flight;

请参见demo

mwkjh3gx

mwkjh3gx2#

如果我理解正确的话,把Flight的第一行作为Source,最后一行作为Destination,那么这就产生了你想要的列表。我不知道它的性能和forpas的相比如何,你只能试试了。

SELECT a.Flight, a.Source, c.Destination
FROM source_destination_flight a,
  (SELECT d.Flight, Min(d.id) AS Minid, Max(d.id) AS Maxid 
    FROM source_destination_flight d GROUP BY Flight) b,
  source_destination_flight c
WHERE a.id = b.Minid
AND c.id = b.Maxid;

相关问题