sql - 无法理解使用 where 和 group by 的子查询代码
问题描述
如果我想将每种产品类型的销售价格与相应产品类型中每个项目的销售价格进行比较,这里是获取它的代码:
SELECT product_type, product_name, sale_price
FROM Product AS P1
WHERE sale_price > (SELECT AVG(sale_price)
FROM Product AS P2
WHERE P1.product_type = P2.product_type
GROUP BY product_type );
我无法理解“where P1.product_type = P2.product_type”的子查询代码。对于子查询之外的 WHERE,应该用它来过滤单行。但是,它如何在子查询中获得单个结果?
解决方案
您要编写的查询:
SELECT product_type, product_name, sale_price
FROM Product AS P1
WHERE sale_price > (
SELECT AVG(sale_price)
FROM Product AS P2
WHERE P1.product_type = P2.product_type
);
这句话为:带来所有大于同类型产品平均值的product
行。子句中的子查询称为相关子查询,并计算具有相同的所有行的平均值(子查询的子句实现相关性)。sale_price
sale_price
where
product_type
where
这也可以用窗口函数表示:
select *
from (
select
p.*,
avg(sale_price) over(partition by product_type) avg_price_by_product_type
from product p
) t
where sale_price > avg_price_by_product_type
推荐阅读
- python - 在 Heroku 上部署 playwright-python
- logging - 如何在手动创建的记录器(dotnet core 3.1)中配置 LogLevel
- python - 在django表单中成功提交表单后如何将address.pk作为参数传递?
- python - Telegram Bot API:如何使用 CallbackQuery.data 获取 InlineKeyboardButton 的文本?
- mysql - 如何查找 SQL 中缺勤或迟到的学生的总百分比?
- scala - Kafka Streams:无法解析重载方法
- tableau-api - 每个粒度的高价值
- c++ - 在 OpenMesh 中按名称删除属性
- java - PGraphics2D 应该实现可克隆但抛出异常
- swift - 将 3D 对象添加到 ARGeoAnchor