Mysql 从另一个表presto进行时间范围有限的聚合

Mysql 从另一个表presto进行时间范围有限的聚合,mysql,sql,presto,Mysql,Sql,Presto,我有一个包含日期、productID、amount和userid的表。 看起来像这样 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

我有一个包含日期、productID、amount和userid的表。 看起来像这样

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

result
productID   sum(amount)
22551   40
22225   40
55521   50
我还有一个表,它将用作聚合中的引用。 第二个表包含productID、开始日期、结束日期

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中的sumamount。预期结果如下所示

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

result
productID   sum(amount)
22551   40
22225   40
55521   50
使用聚合

select t1.productid
     , sum(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.product
这看起来像是一个连接和分组依据:


@RaymondNijland当我编辑你给出的日期时vote@RaymondNijland对不起,我猜错了没问题。。Anny我将如何删除我的评论,因为您的答案已更改为能够给出正确结果的内容。