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

标签 sql postgresql group-by subquery where-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
                    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/

相关文章:

sql - 具有优先级属性的表连接

mysql - 在一个时间范围内分组为 5 分钟的间隔

postgresql - 当我尝试恢复 PostgreSQL 转储时出现很多 "invalid command\N"

windows - postgresql-8.4.7 for Windows编译

postgresql - pgagent centos 6.2

mysql - 如何获取多个日期范围的 mysql 结果?

sql - 顺序更新语句

mongodb - 在 mongoDb 中分组而不计数

mysql - 按问题进行计数和分组

indexing - 如何访问数据框的(多)索引?