如何在 PostgreSQL 中找到一个值保持相同状态的最大时间差?
How to find the max time difference in PostgreSQL that a value stayed on the same state?
我正在为一个大学项目工作,我想到了这个:
我有一个 table 这样的:
我想获得执行器处于某个状态的最长持续时间。例如,cool0 是 18 分钟。
结果 table 应如下所示:
NAME COOL0
State False
Duration 18
这是一个缺口和孤岛问题。你的数据有点难以理解,但我认为:
select actuator, state, min(actuator_time), max(actuator_time)
from (select t.*,
row_number() over (partition by actuator order by actuator_time) as seqnum,
row_number() over (partition by actuator, state order by actuator_time) as seqnum_s
from t
) t
group by actuator, (seqnum- seqnum_s)
对于每个执行器的最大值,使用 distinct on
:
select distinct on (actuator) actuator, state, min(actuator_time), max(actuator_time)
from (select t.*,
row_number() over (partition by actuator order by actuator_time) as seqnum,
row_number() over (partition by actuator, state order by actuator_time) as seqnum_s
from t
) t
group by actuator, (seqnum- seqnum_s)
order by actuator, max(actuator_time) - min(actuator_time) desc;
我正在为一个大学项目工作,我想到了这个:
我有一个 table 这样的:
我想获得执行器处于某个状态的最长持续时间。例如,cool0 是 18 分钟。
结果 table 应如下所示:
NAME COOL0
State False
Duration 18
这是一个缺口和孤岛问题。你的数据有点难以理解,但我认为:
select actuator, state, min(actuator_time), max(actuator_time)
from (select t.*,
row_number() over (partition by actuator order by actuator_time) as seqnum,
row_number() over (partition by actuator, state order by actuator_time) as seqnum_s
from t
) t
group by actuator, (seqnum- seqnum_s)
对于每个执行器的最大值,使用 distinct on
:
select distinct on (actuator) actuator, state, min(actuator_time), max(actuator_time)
from (select t.*,
row_number() over (partition by actuator order by actuator_time) as seqnum,
row_number() over (partition by actuator, state order by actuator_time) as seqnum_s
from t
) t
group by actuator, (seqnum- seqnum_s)
order by actuator, max(actuator_time) - min(actuator_time) desc;