MySQL 查询根据日期查找最长的值序列

MySQL query to find the longest sequence of value based on date

我想根据日期列找到给定值的最长序列,例如给定 table:

+-------+-------------------+
|value  |timestamp          |
+-------+-------------------+
|1      |2021-02-20 13:31:21|
|0      |2021-02-20 13:31:58|
|1      |2021-02-20 13:32:00|
|1      |2021-02-20 13:33:24|
|1      |2021-02-20 13:34:12|
|0      |2021-02-20 13:36:51|

对于值“1”,最长的序列是 2 分 12 秒长,这怎么能做到?

希望有人能够提供帮助!谢谢!

您可以通过累计 0 个值的数量来分配一个组。然后聚合以查看所有组:

select min(timestamp), max(timestamp)
from (select t.*,
             sum(value = 0) over (order by timestamp) as grp
      from t
     ) t
where value = 1
group by grp;

求差取最长周期:

select min(timestamp), max(timestamp),
       second_to_time(to_seconds(max(timestamp)) - to_seconds(min(timetamp)))
from (select t.*,
             sum(value = 0) over (order by timestamp) as grp
      from t
     ) t
where value = 1
group by grp
order by to_seconds(max(timestamp)) - to_seconds(min(timetamp)) desc
limit 1;