gpt4 book ai didi

mysql - 来自另一个表的有限时间范围的聚合

转载 作者:行者123 更新时间:2023-11-29 09:34:46 24 4
gpt4 key购买 nike

我有一个包含日期、产品 ID、金额、用户 ID 的表。看起来像这样

table 1
date userid amount productID
2019-07-01 111 10 43214
2019-07-15 112 20 22551
2019-07-19 113 10 22551
2019-08-19 114 30 22551
2019-08-20 111 20 52212
2019-08-20 115 40 22225
2019-08-20 155 50 55521
2019-08-23 155 50 55521
2019-08-23 155 50 55521

我还有一个表格将用作聚合时的引用。第二个表包含productID、start_date、end_date。

table 2
product ID start_date end_date
22551 2019-07-19 2019-08-20
22225 2019-07-19 2019-08-20
55521 2019-07-19 2019-08-20

期望的结果是根据表 2 中的规则计算表 1 中的总和(金额)。期望的结果如下所示

result
productID sum(amount)
22551 40
22225 40
55521 50

最佳答案

这看起来像JOINGROUP BY:

select t1.productId, sum(t1.amount)
from table1 t1 join
table2 t2
on t1.productId = t2.productId and
t1.date >= t2.start_date and
t1.date <= t2.end_date
group by t1.productId;

关于mysql - 来自另一个表的有限时间范围的聚合,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57869808/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com