评估移动由每个 ID 创建的最后 5 个订单

Posted

技术标签:

【中文标题】评估移动由每个 ID 创建的最后 5 个订单【英文标题】:Evaluate moving last 5 orders created by each ID 【发布时间】:2021-09-06 02:55:13 【问题描述】:

我有下表:

create table DemoTable
(
   buyer_id INT,
   order_id INT,
   variable_a INT,
   created_date datetime
);

INSERT INTO DemoTable(buyer_id, order_id, variable_a, created_date) VALUES (54, 75, 609, '2019-06-02 16:46:53');
INSERT INTO DemoTable(buyer_id, order_id, variable_a, created_date) VALUES (54, 74, 363, '2019-06-01 22:00:00');
INSERT INTO DemoTable(buyer_id, order_id, variable_a, created_date) VALUES (54, 73, 300, '2019-06-01 20:00:02');
INSERT INTO DemoTable(buyer_id, order_id, variable_a, created_date) VALUES (54, 72, 225, '2019-06-01 18:12:03');
INSERT INTO DemoTable(buyer_id, order_id, variable_a, created_date) VALUES (54, 71, 110, '2019-06-01 16:10:03');
INSERT INTO DemoTable(buyer_id, order_id, variable_a, created_date) VALUES (54, 55, 213, '2019-06-01 14:22:03');
INSERT INTO DemoTable(buyer_id, order_id, variable_a, created_date) VALUES (54, 51, 225, '2018-12-01 16:12:03');
INSERT INTO DemoTable(buyer_id, order_id, variable_a, created_date) VALUES (54, 32, 110, '2018-12-01 15:10:03');
INSERT INTO DemoTable(buyer_id, order_id, variable_a, created_date) VALUES (54, 12, 213, '2018-12-01 12:22:03');
buyer_id order_id variable_a created_date
54 75 609 2019-06-02 16:46:53
54 74 363 2019-06-01 22:00:00
54 75 300 2019-06-01 20:00:02
54 73 225 2019-06-01 18:12:03
54 72 110 2019-06-01 16:10:03
54 55 213 2019-06-01 14:22:03
54 51 225 2018-12-01 16:12:03
54 32 110 2018-12-01 15:10:03
54 12 213 2018-12-01 12:22:03

我需要做的是评估由 buy_id 创建的最后 5 个订单 (l5o),它是每个 order_id 的移动 l5o。下面的例子是对最后5个订单的variable_a进行平均:

buyer_id variable_a_avg_l5o created_date
54 321.4 2019-06-02
54 242.2 2019-06-01

2019-06-02:(609+363+300+225+110)/5 = 321.4

2019-06-01:(363+300+225+110+213)/5 = 242.2

请指导我如何应用此逻辑。请注意,我使用的是 presto,但尚不支持相关子查询。

谢谢!

【问题讨论】:

【参考方案1】:

如果我理解正确,您只需要一个带有窗口框架规范的窗口函数:

select t.*,
       avg(variable_a) over (partition by buyer_id
                             order by created_date
                             rows between 4 preceding and current row
                            ) as avg_5
from t;

【讨论】:

以上是关于评估移动由每个 ID 创建的最后 5 个订单的主要内容,如果未能解决你的问题,请参考以下文章

AHP层次分析法解决用户价值评估

节点编辑器评估的高效图遍历

Spring Boot:迭代和评估所有(活动)会话

你应该知道的模型评估的五个方法

海氏评估法 - 职位评估法

Python:AND评估的优化[重复]