【问题标题】:Trying to set up a subquery to compare an average price to all prices for a given category尝试设置子查询以将平均价格与给定类别的所有价格进行比较
【发布时间】:2020-06-09 23:10:29
【问题描述】:

使用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 行:平均价格在哪里

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

【问题讨论】:

    标签: sql postgresql subquery


    【解决方案1】:

    使用窗口函数:

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

    【讨论】:

    • 感谢您的回答!并且向我介绍了窗口功能:)。欣赏它。
    • @user13717038 。 . .如果这回答了您的问题,那么您应该接受答案(在这种情况下没有其他答案)。
    猜你喜欢
    • 2023-03-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-01-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多