如果我想将每种产品类型的售价与相应产品类型中每个商品的售价进行比较,请使用以下代码获取它:
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
关于sql - 无法理解使用 where 和 group by 的子查询代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61962524/