【发布时间】:2021-06-29 19:24:17
【问题描述】:
我有日期时间表,我需要选择连续的时间间隔
我的桌子:
| Id | Time |
|---|---|
| 1 | 2021-01-01 10:00:00 |
| 1 | 2021-01-01 10:01:00 |
| 1 | 2021-01-01 10:02:00 |
| 1 | 2021-01-01 10:04:00 |
| 2 | 2021-01-01 10:03:00 |
| 2 | 2021-01-01 10:04:00 |
| 2 | 2021-01-01 10:06:00 |
| 2 | 2021-01-01 10:07:00 |
我需要的结果:
| id | date_from | date_to |
|---|---|---|
| 1 | 2021-01-01 10:00:00 | 2021-01-01 10:02:00 |
| 1 | 2021-01-01 10:04:00 | 2021-01-01 10:04:00 |
| 2 | 2021-01-01 10:03:00 | 2021-01-01 10:04:00 |
| 2 | 2021-01-01 10:06:00 | 2021-01-01 10:07:00 |
我试过这样,但做不到
select id,
min(date_from) over
(partition by id, date_to
order by id)
as date_from,
max(date_to) over
(partition by id, date_from
order by id)
as date_to
from (
select id,
MIN(time) over
(PARTITION by id,
diff2 between 0 and 60
ORDER BY id, time)
as date_from,
max(MINUTE) over
(PARTITION by id,
diff between 0 and 60
ORDER BY id, time)
as date_to
from (
select *,
unix_timestamp(date_lead) - unix_timestamp(time)
as diff,
unix_timestamp(time) - unix_timestamp(date_lag)
as diff2
from (
select id, time,
NVL(LEAD(time) over
(PARTITION by id
ORDER BY id, time), time)
as date_lead,
NVL(LAG(time) over
(PARTITION by id
ORDER BY id, time), time)
as date_lag
from my_table)
)
)
【问题讨论】:
-
您在使用 Oracle 吗?如果是这样,请使用您的实际数据库更新您问题下的标签。
标签: sql postgresql