MySQL查询根据日期查找最长的值序列
Posted
技术标签:
【中文标题】MySQL查询根据日期查找最长的值序列【英文标题】:MySQL query to find the longest sequence of value based on date 【发布时间】:2021-06-20 15:17:15 【问题描述】:我想根据日期列找到给定值的最长序列,例如给定表格:
+-------+-------------------+
|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 秒,如何做到这一点?
希望有人能提供帮助!谢谢!
【问题讨论】:
哪个版本的mysql,到目前为止你尝试过什么? 请注意,这是一个标准的“差距和岛屿”问题 【参考方案1】:您可以通过累计计算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;
【讨论】:
以上是关于MySQL查询根据日期查找最长的值序列的主要内容,如果未能解决你的问题,请参考以下文章