计算高于该类别平均价格的每个类别的项目
Counting items per category above the avg price for that category
使用 Postgresql 12.2
我正在开发一个 table,其中包含 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
;
我试图扩展它以计算每种类型的 meal_ids:
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 行:select m.*, count(meal_id)"
我不确定解决方法。
谢谢!!
我想你想要:
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
使用 Postgresql 12.2
我正在开发一个 table,其中包含 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
;
我试图扩展它以计算每种类型的 meal_ids:
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 行:select m.*, count(meal_id)"
我不确定解决方法。
谢谢!!
我想你想要:
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