【问题标题】:How to define EventStop timeStamp based on condition using tSQL?如何使用 SQL 根据条件定义事件停止时间戳?
【发布时间】:2020-03-17 13:26:33
【问题描述】:

我想弄清楚以下几点:

  • 我有一个引用相应机器的时间戳列表 状态(1 或 0)
  • 我有兴趣生成一个新表,其中:机器跳转到机器状态 1 (START) 的第一个时间戳和机器崩溃的时间戳 (machinestate = 0, reasonID = 15) (END)

图片 1

图片 2

【问题讨论】:

  • 看起来你需要 LAG/LEAD 来做这个。 MIN/MAX 很可能不起作用。

标签: sql tsql group-by gaps-and-islands


【解决方案1】:

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

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-06-13
    • 1970-01-01
    • 1970-01-01
    • 2019-06-10
    • 2020-06-02
    相关资源
    最近更新 更多