首页 > 解决方案 > 在 SQL 列中跟踪时间序列事件的状态

问题描述

这看起来很简单,但我无法弄清楚,在 SQL Server 中工作。我有时间序列数据,我想要一个列来跟踪每一行的 ON/OFF 事件的状态,所以当有一个 ON 事件时,Desired Output 列将为每个后续事件都有一个 1,直到有一个 OFF 事件。请看下面的例子。非常感谢!

时间戳 事件 期望的输出
1:01 1
1:02 离开 0
1:04 其他 0
1:05 其他 0
1:06 1
1:10 其他 1
1:12 其他 1
1:14 离开 0
1:15 其他 0

标签: sqlsql-servertsqltime-series

解决方案


您可以比较 ON 和 OFF 的累积计数:

select t.*,
       (case when sum(case when event = 'ON' then 1 else 0 end) over (order by timestamp) >
                  sum(case when event = 'OFF' then 1 else 0 end)
             then 1 else 0
        end) as desired
from t;

推荐阅读