Du skal trække tidsforskellen fra hinanden i dens konstituerende dag-, time-, minut- og sekundelementer, kombinere antallet af dage * 24 med antallet af timer og sætte det sammen igen.
Når du trækker datoer fra, får du forskellen som antallet af dage, så du skal konvertere brøkdelen til de andre elementer, hvilket du kan gøre med en kombination af trunc og mod; ved at bruge en CTE for at gøre dette lidt nemmere at følge og vise hver værdi for sig såvel som kombineret i en enkelt streng:
with y as (
select id, end_time - start_time as runtime
from mytable
)
select id,
runtime,
trunc(runtime) as days,
24 * trunc(runtime) as day_hours,
trunc(24 * mod(runtime, 1)) as hours,
trunc(60 * mod(24 * (runtime), 1)) as minutes,
trunc(60 * mod(24 * 60 * (runtime), 1)) as seconds,
lpad(24 * trunc(runtime)
+ trunc(24 * mod(runtime, 1)), 2, '0')
||':'|| lpad(trunc(60 * mod(24 * (runtime), 1)), 2, '0')
||':'|| lpad(trunc(60 * mod(24 * 60 * (runtime), 1)), 2, '0')
as runtime
from y;
ID RUNTIME DAYS DAY_HOURS HOURS MINUTES SECONDS RUNTIME
---------- ---------- ---------- ---------- ---------- ---------- ---------- --------
1 .184918981 0 0 4 26 16 04:26:16
2 1.14465278 1 24 3 28 18 27:28:18
Du kan også konvertere datoerne til tidsstempler for beregningen, hvilket giver dig en intervaltype, og derefter bruge extract
funktion for at få elementerne i stedet for; hovedstolen er dog den samme:
with y as (
select id,
cast(end_time as timestamp) - cast (start_time as timestamp) as runtime
from mytable
)
select id,
runtime,
extract (day from runtime) as days,
24 * extract (day from runtime) as day_hours,
extract (hour from runtime) as hours,
extract (minute from runtime) as minutes,
extract (second from runtime) as seconds,
lpad(24 * extract (day from runtime) + extract (hour from runtime), 2, '0')
||':'|| lpad(extract (minute from runtime), 2, '0')
||':'|| lpad(extract (second from runtime), 2, '0')
as runtime
from y;
ID RUNTIME DAYS DAY_HOURS HOURS MINUTES SECONDS RUNTIME
---------- ----------- ---------- ---------- ---------- ---------- ---------- --------
1 0 4:26:17.0 0 0 4 26 17 04:26:17
2 1 3:28:18.0 1 24 3 28 18 27:28:18
Eller en lille variation, få forskellen fra datoerne og derefter konvertere det til et interval:
with y as (
select id,
numtodsinterval(end_time - start_time, 'DAY') as runtime
from mytable
)
...
SQL Fiddle-demo.