You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

PostgreSQL如何计算同类型其余产品订单平均值并筛选符合条件产品

问题描述

我有一张名为Products的表,结构如下:

+-----------+-----------+----------+
|ProductCode|ProductType|   ....   |
+-----------+-----------+----------+
|   ref01   |   BOOKS   |   ....   |
|   ref02   |   ALBUMS  |   ....   |
|   ref06   |   BOOKS   |   ....   |
|   ref04   |   BOOKS   |   ....   |
|   ref07   |   ALBUMS  |   ....   |
|   ref10   |   TOYS    |   ....   |
|   ref13   |   TOYS    |   ....   |
|   ref09   |   ALBUMS  |   ....   |
|   ref29   |   TOYS    |   ....   |
|   .....   |   .....   |   ....   |
+-----------+-----------+----------+

另有一张名为Sales的表,结构如下:

+-----------+-----------+----------+
|ProductCode|   Orders  |   ....   |
+-----------+-----------+----------+
|   ref01   |     15    |   ....   |
|   ref02   |     12    |   ....   |
|   ref06   |     20    |   ....   |
|   ref04   |     14    |   ....   |
|   ref07   |     11    |   ....   |
|   ref10   |     19    |   ....   |
|   ref13   |      3    |   ....   |
|   ref09   |      9    |   ....   |
|   ref29   |      5    |   ....   |
|   .....   |   .....   |   ....   |
+-----------+-----------+----------+

需要筛选出订单量高于同类型其余所有产品订单平均值的产品,使用PostgreSQL实现,且不能使用WITH、OVER、LIMIT、PARTITION关键字。

实现SQL
SELECT s.ProductCode, s.Orders
FROM Products p
INNER JOIN Sales s 
ON p.ProductCode = s.ProductCode
WHERE s.Orders > (
    SELECT AVG(s2.Orders)
    FROM Products p2
    INNER JOIN Sales s2 
    ON p2.ProductCode = s2.ProductCode
    WHERE p2.ProductType = p.ProductType
    AND p2.ProductCode != p.ProductCode
)
逻辑说明
  • 外层查询关联Products和Sales表,获取每个产品的类型、编码、对应订单量
  • 关联子查询会匹配与外层当前产品同类型、且产品编码不一致的所有产品,计算这部分产品的平均订单量
  • WHERE条件过滤出订单量大于同类型其他产品平均订单的产品,完全匹配需求的计算逻辑,且未使用禁用关键字。

内容的提问来源于stack exchange,提问作者Hayul Kim

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.26 18:15:08