请求协助(postgresql)min/max函数

oknrviil  于 2021-08-09  发布在  Java
关注(0)|答案(2)|浏览(394)

我是博士后的新手,我提出了以下问题。如果有城市的经济价格比商业价格便宜,我需要回答这个问题。目前我的要求如下:

with cte_money as (
    select  
        ad.city ->> 'ru' as city,
        fare_conditions, 
        amount
    from ticket_flights tf   
    join flights as f using(flight_id)
    join airports_data as ad on f.arrival_airport = ad.airport_code 
    order by city, fare_conditions asc
    )
    select  
        city,
        (select max(amount) where fare_conditions = 'Economy') as Max_Economy,
        (select min(amount) where fare_conditions = 'Business') as Min_Business
    from cte_money
    group by city, fare_conditions
    order by city asc

结果如下(黄色):

如何将同一城市的最大值与最小值合并在一行中,并相互比较?总之,我只需要显示经济舱比商务舱便宜的城市。先谢谢你

6rvt4ljy

6rvt4ljy1#

我理解您的问题和模式,不需要cte或嵌套查询。您可以使用聚合和 having 过滤条款:

select ad.city ->> 'ru' as city,
from ticket_flights tf   
join flights as f using(flight_id)
join airports_data as ad on f.arrival_airport = ad.airport_code 
group by ad.city ->> 'ru'
having 
    max(amount) filter (where fare_conditions = 'Economy') 
    < min(amount) filter(where fare_conditions = 'Business') 
order by city

你可以重复条件句 min() 以及 max()select 子句,如果要在结果集中显示它们。

axr492tv

axr492tv2#

对于这个groupby查询,当您将条件放入聚合时,不需要子选择。然后,您可以使用having子句轻松筛选更便宜的经济舱:

with cte_money as (
    select  
        ad.city ->> 'ru' as city,
        fare_conditions, 
        amount
    from ticket_flights tf   
    join flights as f using(flight_id)
    join airports_data as ad on f.arrival_airport = ad.airport_code 
    order by city, fare_conditions asc
    )
    select  
        city,
        max(CASE WHEN fare_conditions = 'Economy' THEN amount ELSE NULL END) as Max_Economy,
        min(CASE WHEN fare_conditions = 'Business' THEN amount ELSE NULL END) as Min_Business 
    from cte_money
    group by city, fare_conditions
    HAVING max(CASE WHEN fare_conditions = 'Economy' THEN amount ELSE NULL END) <= min(CASE WHEN fare_conditions = 'Business' THEN amount ELSE NULL END)
    order by city asc

相关问题