两个时间序列事件之间的累积和

Cumulative sum between two timeserie events

我在 bigquery 中有以下时间序列数据:

Timestamp                   EventID   Value
2022-03-05 06:00:10          1         NULL
2022-03-05 06:00:11          3         5
2022-03-05 06:00:12          2         3  
2022-03-05 06:00:13          3         2 
2022-03-05 06:00:14          4         1          
2022-03-05 06:00:17          2         6 
2022-03-05 06:00:17          5         NULL
2022-03-05 06:30:15          1         NULL
2022-03-05 06:30:18          3         2 
2022-03-05 06:31:22          2         4 
2022-03-05 06:35:56          3         3 
2022-03-05 06:36:18          4         1 
2022-03-05 06:39:17          2         2
2022-03-05 06:50:24          5         NULL

我想编写一个 SQL 查询来对 eventId 1 和 eventId 5 之间具有相同 eventID 的值求和。 输出将如下所示:

StartEventId    EndEventId      StartTime             EndTime              total_2   total_3   total_4 
1               5               2022-03-05 06:00:10   2022-03-05 06:00:17   9        7          1
1               5               2022-03-05 06:30:15   2022-03-05 06:50:24   6        5          1 

total_2 是 eventID 1 和 5 之间 eventId 等于 2 的值的总和。total_3 和 total_4 相同。

感谢您的帮助!

考虑以下方法

select min(EventID) StartEventId,  max(EventID) EndEventId,
  min(Timestamp) StartTime,  max(Timestamp) EndTime,
  sum(if(EventID = 2, Value, null)) total_2,
  sum(if(EventID = 3, Value, null)) total_3,
  sum(if(EventID = 4, Value, null)) total_4
from (
  select *, div(countif(EventID in (1,5)) over win - 1, 2) grp
  from your_table
  window win as (order by Timestamp, EventID)
)
group by grp            

如果应用于您问题中的示例数据 - 输出为