sql - 尝试设置子查询以将平均价格与给定类别的所有价格进行比较
问题描述
使用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 行:平均价格
我不确定为什么会收到此错误消息。谢谢!
解决方案
使用窗口函数:
select m.*
from (select m.*, avg(price) over (partition by type) as type_price
from meals m
) m
where price > type_price;
推荐阅读
- c# - WPF ICommand CanExecute 从其他线程更新
- reactjs - 如何在本机反应中制作动态标签视图屏幕
- ldap - Quarkus LDAP 获取用户数据
- microsoft-graph-api - Microsoft.Graph.Core 创建订阅“拒绝访问”
- ios - SKReceiptRefreshRequest 在带有 .storekit 配置文件的 Xcode 12.2 中总是失败
- sql-server - 选择一条记录,在它之前抓取“n”条记录,然后遍历它们以查看它们是否是连续的
- android - 从 ExpandableList 适配器中删除项目
- c - 当我将链表实现出列时从节点返回字符串值时出现奇怪的字符串值
- python - 在数据库关系中添加重复行
- excel - Excel - 模式如果