Если у вас никогда не будет двух STOP подряд и вам нужно последнее значение START, используйте lag
, чтобы найти время последнего запуска. И вычесть из текущего времени:
create table t (
id int, status varchar2(5), date_cr timestamp, hash varchar2(32)
);
insert into t values (1, 'STOP', to_date ( '26.03.2020 14:45:41', 'dd.mm.yyyy hh24:mi:ss' ), '7A8E93CA359A39133B6AAC93123' );
insert into t values (2, 'START', to_date ( '26.03.2020 12:23:47', 'dd.mm.yyyy hh24:mi:ss' ), '7A8E93CA359A39133B6AAC93127' );
insert into t values (3, 'STOP', to_date ( '26.03.2020 11:12:41', 'dd.mm.yyyy hh24:mi:ss' ), '7A8E93CA359A39133B6AAC93111' );
insert into t values (4, 'START', to_date ( '26.03.2020 10:56:40', 'dd.mm.yyyy hh24:mi:ss' ), '7A8E93CA359A39133B6AAC93111' );
insert into t values (5, 'STOP', to_date ( '26.03.2020 10:23:41', 'dd.mm.yyyy hh24:mi:ss' ), '7A8E93CA359A39133B6AAC93B09' );
insert into t values (6, 'START', to_date ( '26.03.2020 08:13:40', 'dd.mm.yyyy hh24:mi:ss' ), '7A8E93CA359A39133B6AAC93B09' );
insert into t values (7, 'START', to_date ( '26.03.2020 07:23:41', 'dd.mm.yyyy hh24:mi:ss' ), '7A8E93CA359A39133B6AAC93123' );
insert into t values (8, 'STOP', to_date ( '26.03.2020 06:18:56', 'dd.mm.yyyy hh24:mi:ss' ), '7A8E93CA359A39133B6AAC93123' );
insert into t values (9, 'START', to_date ( '26.03.2020 04:12:23', 'dd.mm.yyyy hh24:mi:ss' ), '7A8E93CA359A39133B6AAC93123' );
commit;
select id,
status,
date_cr,
case
when status = 'STOP' then
date_cr - lag ( date_cr ) over (
order by date_cr
)
end tm
from t
order by date_cr desc;
ID STATUS DATE_CR TM
1 STOP 26-MAR-2020 14.45.41.000000000 +00 02:21:54.000000
2 START 26-MAR-2020 12.23.47.000000000 <null>
3 STOP 26-MAR-2020 11.12.41.000000000 +00 00:16:01.000000
4 START 26-MAR-2020 10.56.40.000000000 <null>
5 STOP 26-MAR-2020 10.23.41.000000000 +00 02:10:01.000000
6 START 26-MAR-2020 08.13.40.000000000 <null>
7 START 26-MAR-2020 07.23.41.000000000 <null>
8 STOP 26-MAR-2020 06.18.56.000000000 +00 02:06:33.000000
9 START 26-MAR-2020 04.12.23.000000000 <null>