MySQL启动和停止设备的时间

时间:2012-10-16 23:03:51

标签: mysql sql

我有一个包含趋势数据的数据库,结构如下:

[Timestamp, System_State]
2012-01-01 00:00:00, 1
2012-01-01 00:01:00, 1
2012-01-01 00:02:00, 0
2012-01-01 00:03:00, 1
2012-01-01 00:04:00, 1
2012-01-01 00:05:00, 0
...

现在我需要编写一个SQL查询来了解系统何时启动(system_state从0更改为1)以及何时停止(状态从1更改为0)。除了使用光标,我还有其他选择吗?

感谢。

1 个答案:

答案 0 :(得分:1)

这样的事情(这是T-SQL,即SQL Server,但也可能适用于MySql)

declare @t table (eventTime datetime, eventState bit)

insert @t select '2012-01-01 00:00:00', 1
union all select '2012-01-01 00:01:00', 1
union all select '2012-01-01 00:02:00', 0
union all select '2012-01-01 00:03:00', 1
union all select '2012-01-01 00:04:00', 1
union all select '2012-01-01 00:05:00', 0

select *
from
(
    select eventTime, eventState, row_number() over (order by eventTime, eventState)r 
    from @t
) a
inner join
(
    select eventTime, eventState, row_number() over (order by eventTime, eventState)r 
    from @t
) b
on a.r = b.r-1
where a.eventState <> b.eventState

- alteratively:

select *
from @t a
where exists (
    select 1
    from @t b
    where a.eventTime > b.eventTime
    and a.eventState != b.eventState
    and not exists
    (
        select 1
        from @t c
        where a.eventTime > c.eventTime
        and b.eventTime < c.eventTime
    )
)
order by eventTime

- 或

select *
from @t a
inner join @t b
    on a.eventTime > b.eventTime
    and a.eventState != b.eventState
left outer join @t c
    on a.eventTime > c.eventTime
    and b.eventTime < c.eventTime
where c.eventState is null
order by a.eventTime