基于两列日期时间条件的 SQL SUM

问题描述

请帮助我了解此 sql 语法。想要根据另一个表中每分钟的唯一值将 avr 值放入表一。 最佳/彼得

表 1

Activity,starttime,endtime 
Dance,2010-01-01 15:00,2010-01-01 15:05

表 2

Activity,Minute,Value
Dance,50
Dance,2010-01-01 15:01,10
Dance,2010-01-01 15:02,2010-01-01 15:03,20
Dance,2010-01-01 15:04,10

想要的结果

Activity,endtime,avr Value
Dance,2010-01-01 15:05,20

解决方法

一种方法是相关子查询:

select t1.*,(select avg(t2.value)
        from table2 t2
        where t2.activity = t1.activity and
              t2.minute >= t1.starttime and
              t2.minute < t1.endtime
       ) as avg_value
from table1 t1;