I want to find the time gaps for different days between one end_time and nearest start_time in another record which is stored as follows:
record_id | start_time | end_time
120 | 2019-09-01 08:05:00 | 2019-09-01 10:35:00
103 | 2019-09-01 10:45:00 | 2019-09-01 14:00:00
108 | 2019-09-01 14:30:00 | 2019-09-01 18:00:00
225 | 2019-09-02 07:30:00 | 2019-09-02 10:30:00
245 | 2019-09-02 10:30:00 | 2019-09-02 13:40:00
250 | 2019-09-02 14:00:00 | null
Start_time and End_time are timestamp columns.
Expected output is:
2019-09-01 | 10
2019-09-01 | 30
2019-09-02 | 0
2019-09-02 | 20
Can anyone please help me on this?
Here you will need to use LEAD analytic function.
select end_time,
lead(start_time) over (order by start_time) as nextr -- this is the start_time from the next record
from your_table;
Then you can select (next_record - start_time) to get the tipe gap and format it in away you want.
Hope this will help you. Here is the example of what you need: http://sqlfiddle.com/#!4/23457/3
First I have created the example table:
create table your_table (
record_id number(10),
start_time date,
end_time date);
insert into your_table values (101, to_date('02.10.2019 08:00:00','dd.mm.yyyy hh24:mi:ss'), to_date('02.10.2019 12:00:00','dd.mm.yyyy hh24:mi:ss'));
insert into your_table values (102, to_date('02.10.2019 12:30:00','dd.mm.yyyy hh24:mi:ss'), to_date('03.10.2019 12:00:00','dd.mm.yyyy hh24:mi:ss'));
insert into your_table values (103, to_date('03.10.2019 12:10:00','dd.mm.yyyy hh24:mi:ss'), to_date('03.10.2019 15:00:00','dd.mm.yyyy hh24:mi:ss'));
insert into your_table values (104, to_date('03.10.2019 15:15:00','dd.mm.yyyy hh24:mi:ss'), to_date('03.10.2019 18:00:00','dd.mm.yyyy hh24:mi:ss'));
And on the right you have the code that will return the result you asked for:
select start_time,
--lead(start_time) over (order by start_time) as nextr,
(nvl(((lead(start_time) over (order by start_time)) - end_time), 0)) * 24 * 60 AS "Time gap"
from your_table;
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.