【问题标题】:Counting items per category above the avg price for that category计算高于该类别平均价格的每个类别的项目
【发布时间】:2020-10-18 07:02:45
【问题描述】:

使用 Postgresql 12.2

我正在处理一张表格,其中包含 meal_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
;

我已尝试扩展它以计算每种类型的餐食 ID:

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)"

我不确定解决方法。

谢谢!!

【问题讨论】:

    标签: sql postgresql select average window-functions


    【解决方案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
    

    【讨论】:

    • 成功了,谢谢!我不明白为什么需要计算 * 而不是只计算meal_ids,但我知道选择类型需要按类型分组。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-03-23
    • 2011-10-16
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多