首页 > 解决方案 > 尝试设置子查询以将平均价格与给定类别的所有价格进行比较

问题描述

使用Postgresql 12.2

我正在处理一张表,其中包含 meal_id(特定餐点实例)、类型(菜品类型)、客户 ID、餐品价格等列。有 6 种美食类型(意大利菜、日本菜等)。我需要找到每种菜肴的平均价格,然后显示每种类型的哪些特定餐食 ID 的价格高于该类型的平均价格。

当我尝试这个时:

select m1.*  
 from meals m1  
 join (select avg(price) 
       from meals  
       group by type) average  
 on meal_id=meal_id  
 where price > average  
 group by type;

我收到错误消息:

错误:运算符不存在:整数 > 记录第 7 行:平均价格

我不确定为什么会收到此错误消息。谢谢!

标签: sqlpostgresqlsubquery

解决方案


使用窗口函数:

select m.*
from (select m.*, avg(price) over (partition by type) as type_price
      from meals m
     ) m
where price > type_price;

推荐阅读