【发布时间】:2021-12-23 13:42:40
【问题描述】:
我有一张表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 | .... |
| ..... | ..... | .... |
+-----------+-----------+----------+
我正在尝试查找订购量超过所有其他同类产品的平均值的产品。
通过手动计算,结果会是这样的:
+-----------+-----------+----------+
|ProductCode| Orders | .... |
+-----------+-----------+----------+
| ref02 | 12 | .... |
| ref06 | 20 | .... |
| ref07 | 11 | .... |
| ref10 | 19 | .... |
| ..... | ..... | .... |
+-----------+-----------+----------+
因此,如果查看类型 ALBUMS 和产品 ref02,那么我需要找到所有其他 ALBUMS 的订单的平均值。
在这种情况下,它是ref06 和ref04 的平均值,但实际表中还有更多。所以我需要做的是:
Since product ref02 is 'ALBUMS', and ref07 and ref09 are also 'ALBUMS'.
So their average is (11+9)/2=10 <12.
Since product ref06 is 'BOOKS', and **ref01** and ref04 are also 'BOOKS'.
So their average is (15+14)/2=14.5 <20.
Since product ref07 is 'ALBUMS', and **ref02** and ref09 are also 'ALBUMS'.
So their average is (12+9)/2=10.5<11.
Since product ref10 is 'TOYS', and ref13 and ref29 are also 'TOYS'
So their average is (3+5)/2=4<19.
The rest does not satisfy the condition thus will not be in the result.
我知道如何并且能够找到同一类型下所有产品的订单平均值,但我不知道如何找到同一类型下所有其他产品的订单平均值。
我正在使用 PostgreSQL,但不能使用以下任何关键字:WITH、OVER、LIMIT、PARTITION。
【问题讨论】:
-
您为什么不想要使用具有窗口功能的卓越解决方案?
-
如果这是一个练习或家庭作业,那是一个非常愚蠢的禁止使用modern SQL
-
@ErwinBrandstetter 很抱歉给您带来麻烦,但这是一种练习,并不是我不想使用它们,而是我不被允许使用。
-
@a_horse_with_no_name 我不反对,但那是我正在合作的人...... :( 有什么想法吗?
标签: sql postgresql aggregate window-functions