请求协助(postgresql)最小/最大功能
我是博士后新生,提出了以下问题。我需要回答的问题是,是否有城市的经济价格比商业价格便宜。目前我的请求如下:请求协助(postgresql)最小/最大功能,sql,json,postgresql,select,group-by,Sql,Json,Postgresql,Select,Group By,我是博士后新生,提出了以下问题。我需要回答的问题是,是否有城市的经济价格比商业价格便宜。目前我的请求如下: 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 airp
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
它给出以下黄色结果:
如何将同一城市的最大值与最小值合并到一行中,并相互比较?总之,我只需要显示经济舱比商务舱便宜的城市。提前感谢您对于此查询分组,当您将条件放入聚合中时,无需进行子选择。然后,您可以使用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
我理解您的问题和模式,不需要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
如果要在结果集中显示条件最小值和最大值,可以在select子句中重复它们