无法理解使用where和group by的子查询代码

i34xakig  于 2021-07-26  发布在  Java
关注(0)|答案(2)|浏览(406)

如果我想将每种产品类型的售价与对应产品类型中每种商品的售价进行比较,下面是代码:

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\u type=p2.product\u type”的子查询代码。对于子查询外部的where,应该使用它来过滤单行。然而,它如何在子查询中得到一个结果呢?

cigdeys3

cigdeys31#

要编写的查询:

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 (the) 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
edqdpe6u

edqdpe6u2#

你在开一个 AVG() ,是一个分组函数。这意味着您将获得子查询返回的所有值的平均值。当您没有选择其他列时,组将假定您将所有列都分组 sales_price 排。
而且,rdbms知道您有一个名为 P1 在主查询中,对于主select返回的每一行,rdbms执行子查询,比较 P1 比较 P2 查询。

相关问题