我有以下 SQL 表:
id time
1 2018-12-30
1 2018-12-31
1 2018-01-03
2 2018-12-15
2 2018-12-30
我想要进行一个查询,该查询将产生以下数据:
id start_time end_time
1 2018-12-30 2018-12-31
1 2018-12-31 2018-01-03
2 2018-12-15 2018-12-30
这是否可以在合理的时间内使用 sql 来完成,或者最好通过其他方式来完成?
失败的方法(需要太多时间):
SELECT id, time as start_time, (
SELECT MIN(time)
FROM table as T2
WHERE T2.id = T1.id
AND T2.time < T1.time
) as end_time
FROM table as T1
我的数据库中有日期,每个日期都有非唯一的 ID。我想计算每个 id 的最近日期之间的时间范围。所以应该对每个id单独进行转换,并且不应该影响其他id。我们甚至可以忘记 ids,想象一下我的数据库中只有一列,即日期。我想对日期进行排序,并使用步骤 1 和容量 2 执行滑动窗口。因此,如果我有 10 个日期,我希望结果中有 9 个时间范围,这些时间范围应该按递增顺序排列。假设我们有四个日期:D1 < D2 < D3 < D4。结果应为 (D1,D2)、(D2,D3)、(D3,D4)
最佳答案
在 MySQL 8.x 中,您可以使用 LEAD()
函数查看下一行:
with x as (
select
id,
time as start_time,
lead(time) over(partition by id order by time) as end_time
from my_table
)
select * from x where end_time is not null
关于mysql - SQL时间点转时间范围,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54315515/