如何使用 SQL 根据条件定义 EventStop timeStamp?

How to define EventStop timeStamp based on condition using tSQL?

我正在尝试弄清楚以下内容:

图片 1

图片2

这是一个典型的间隙和孤岛问题,您打算将具有相同状态的连续行组合在一起。

这是一种使用行号之间的差异来解决它的方法。

select
    equipment_id,
    min(timestamp) event_start,
    max(timestamp) event_stop,
    machine_state_id,
    max(reason_id) reason_id
from (
    select 
        t.*,
        row_number() over(partition by equipment_id order by timestamp) rn1,
        row_number() over(partition by equipment_id, machine_state_id order by timestamp) rn2
    from mytable t
) t
group by equipment_id, machine_state_id, rn1 - rn2
order by equipment_id, event_start