计算高于该类别平均价格的每个类别的商品

时间:2020-06-27 21:24:56

标签: sql postgresql select average window-functions

使用Postgresql 12.2

我正在处理一个表,其中包含以下列:进餐ID(特定进餐实例),类型(美食类型,如意大利,日语等),客户ID,进餐价格等。

我已经成功地使用Windows函数获取了每种烹饪类型的所有商品的列表,而该列表高于该类型的平均价格:

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

我已经尝试扩展它来计算每种类型的餐号:

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

但是我收到错误消息:“错误:列“ m.meal_id”必须出现在GROUP BY子句中或在聚合函数中使用 第1行:选择m。*,count(meal_id)“

我不确定是否有解决方法。

谢谢!

1 个答案:

答案 0 :(得分:1)

我想你想要

select type, count(*) no_meals_over_average
from (
    select 
        m.*, 
        avg(price) over (partition by type) as avg_price_type
    from meals m
) m
where price > avg_price_type
group by type