首页 > 解决方案 > 无法理解使用 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,应该用它来过滤单行。但是,它如何在子查询中获得单个结果?

标签: sqlpostgresqlgroup-bysubquerywhere-clause

解决方案


您要编写的查询:

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_pricesale_pricewhereproduct_typewhere

这也可以用窗口函数表示:

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

推荐阅读