sql - 在 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 |
解决方案
您可以比较 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;
推荐阅读
- spring-boot - 如何在 Drools 中配置流模式
- python - 如何使用 numpy 更优雅地实现这个 for 循环?
- sql-server - SQL Server 联合性能
- javascript - 如何在 JavaScript 中将带有 css 的弹出窗口添加到现有网站(例如 google.com)?
- python - 在每个唯一日期的特定时间从 DF 中的列中查找值
- javascript - 调试项目代码。。为什么没有定义这个函数?
- scala - 组合案例类而不枚举参数
- docker - 运行 docker build 生成以下错误“未知指令:EXPAND-ARCHIVE”
- gulp - 如何在本地运行(来自 Ghost 的 Casper 主题)开发服务器?
- android - 协程挂起函数和阻塞调用