【发布时间】:2021-12-24 04:36:26
【问题描述】:
我问了一个类似的问题,并得到了一些非常好的人的帮助。 How to find the average of all other products in postgresql。 这个问题不是全部,但我认为如果最难的部分可以解决,我可以自己解决剩下的问题,但显然我高估了自己的能力。所以我要发布另一个问题... :)
问题如下。
我有一张表Products,如下所示:
+-----------+-----------+----------+
|ProductCode|ProductType| .... |
+-----------+-----------+----------+
| ref01 | BOOKS | .... |
| ref02 | ALBUMS | .... |
| ref06 | BOOKS | .... |
| ref04 | BOOKS | .... |
| ref07 | ALBUMS | .... |
| ref10 | TOYS | .... |
| ref13 | TOYS | .... |
| ref09 | ALBUMS | .... |
| ref29 | TOYS | .... |
| ref02 | ALBUMS | .... |
| ..... | ..... | .... |
+-----------+-----------+----------+
另一个表 Sales 如下所示:
+-----------+-----------+----------+
|ProductCode| qty | .... |
+-----------+-----------+----------+
| ref01 | 15 | .... |
| ref02 | 12 | .... |
| ref06 | 20 | .... |
| ref04 | 14 | .... |
| ref07 | 11 | .... |
| ref10 | 19 | .... |
| ref13 | 3 | .... |
| ref09 | 9 | .... |
| ref29 | 5 | .... |
| ref02 | 4 | .... |
| ..... | ..... | .... |
+-----------+-----------+----------+
我试图找出比所有其他同类产品的平均订购量高 20% 的产品。
一种产品可以多次订购,每次订购的数量(数量)可能不同。如示例表中的ref02。我只包括了一个示例(ref02),但所有产品都是如此。因此,要查找特定产品的订购次数意味着从该产品的所有订单中找到订购数量的总和。
通过手动计算,结果应该是这样的:
+-----------+-----------+----------+
|ProductCode| qty | .... |
+-----------+-----------+----------+
| ref02 | 16 | .... |
| ref06 | 20 | .... |
| ref07 | 11 | .... |
| ref10 | 19 | .... |
| ..... | ..... | .... |
+-----------+-----------+----------+
因此,如果查看类型 ALBUMS 和产品 ref02,那么我需要找到所有其他 ALBUMS 的订单的平均值。
在这种情况下,它是ref06 和ref04 的平均值,但实际表中还有更多。所以我需要做的是:
Since product ref02 is 'ALBUMS' and there are two orders of ref02, the total orders will be 12+4=16. And ref07 and ref09 are also 'ALBUMS'.
So their average is (11+9)/2=10 < 12+4=16.
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+4)/3=8.3 <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.
我知道如何并且能够找到同一类型下所有产品的订单平均值,但我不知道如何找到同一类型下所有其他产品的订单平均值。
我知道如何通过我从上一个问题How to find the average of all other products in postgresql 中获得的帮助找到所需的产品,但那时每种产品只有一个订单。如果每个产品有多个订单,我不知道如何进行。这是我在开头提到的“高估”位...... :(
我在上一个问题中收到的答案有这个问题: DEMO (db<>fiddle)。演示中的表格与我正在使用的表格更加相似,并且如您所见,一种产品有很多行。 (重复的行是偶然的。值恰好相同)
我正在使用 PostgreSQL,但该练习禁止使用多个关键字,包括:WITH、OVER、LIMIT、PARTITION 或 LATERAL。我意识到它们通常用于我找到的大多数解决方案以及提供给我的解决方案中,但我不能使用它们,因为否则不会返回任何结果...... :(
我知道不允许使用这些关键字会很烦人,但老实说我不知道该怎么做,所以请帮忙! :)
【问题讨论】:
标签: sql postgresql