I have a table where i have some log like this.
select table_name, min(to_char(DATO,'dd.mm.yyyy hh24:mi')) as start_time, max(to_char(DATO,'dd.mm.yyyy hh24:mi')) as end_time from TMP_AUDIT_LOG t where FLAG='Y' and TR_MODE='EXPORT' group by T.TABLE_NAME order by 2
and output is like below
TABLE_NAME START_TIME END_TIME ---------- ---------------- ---------------- MAPTEXT 06.11.2020 17:29 06.11.2020 18:12 COMPONENT 06.11.2020 18:12 06.11.2020 19:18 SETTKONT 06.11.2020 19:18 06.11.2020 20:24 ROUTELOG 06.11.2020 20:24 06.11.2020 20:44 CROSSEC 06.11.2020 20:44 06.11.2020 20:49
But I want to have one more column which will give me total time like below
TABLE_NAME START_TIME END_TIME TOTAL_TIME ---------- ---------------- ---------------- ---------- MAPTEXT 06.11.2020 17:29 06.11.2020 18:12 43m COMPONENT 06.11.2020 18:12 06.11.2020 19:18 1h 6m SETTKONT 06.11.2020 19:18 06.11.2020 20:24 1h 6m ROUTELOG 06.11.2020 20:24 06.11.2020 20:44 24m CROSSEC 06.11.2020 20:44 06.11.2020 20:49 5m
I have tried to minus both time but not getting proper result.
select table_name, start_time, end_time, (to_date(end_time,'dd.mm.yyyy hh24:mi')-to_date(start_time,'dd.mm.yyyy hh24:mi')) as total_time from ( select table_name, min(to_char(DATO,'dd.mm.yyyy hh24:mi')) as start_time, max(to_char(DATO,'dd.mm.yyyy hh24:mi')) as end_time from TMP_EXPORT_WORKSPACE t where FLAG='Y' and TR_MODE='EXPORT' group by T.TABLE_NAME order by 2 ) ;
The output i am getting is below
TABLE_NAME START_TIME END_TIME TOTAL_TIME ---------- ---------------- ---------------- ---------- MAPTEXT 06.11.2020 17:29 06.11.2020 18:12 0.0298611111111111111111111111111111111111 COMPONENT 06.11.2020 18:12 06.11.2020 19:18 0.0458333333333333333333333333333333333333 SETTKONT 06.11.2020 19:18 06.11.2020 20:24 0.0458333333333333333333333333333333333333 ROUTELOG 06.11.2020 20:24 06.11.2020 20:44 0.0138888888888888888888888888888888888889 CROSSEC 06.11.2020 20:44 06.11.2020 20:49 0.003472222222222222222222222222222222222222
Advertisement
Answer
Don’t convert the dates to strings. That makes no sense and only leads to unexpected results. The column dato
is a DATE
and per table you want the minimum dato
and the maximum dato
, so just use MIN(dato)
and MAX(dato)
. Then you want the difference. You get the difference by subtracting one from the other:
select table_name, min(dato) as start_time, max(dato) as end_time, max(dato) - min(dato) as total_time from tmp_audit_log t where flag = 'Y' and tr_mode = 'EXPORT' group by table_name order by start_time;
As dato
is a DATE
, you get the difference as a fraction of days. If you want an INTERVAL
instead, convert from DATE
to TIMESTAMP
:
max(cast(dato as timestamp)) - min(cast(dato as timestamp)) as total_time