在Oracle中将时差转换为给定格式

lex*_*eme 7 sql oracle formatting

如何将EVENT_DATE_B - EVENT_DATE_A多少天转换成字符串HH:MM格式?

A.B*_*ade 5

另一种方法(一个查询可以在不同的日子):

with tt as (
   select numToDsinterval((EVENT_DATE_B - EVENT_DATE_A ), 'DAY') dsint 
     from t)
select (extract(day from dsint)*24)+extract(hour from dsint) || 
       ':' ||extract(minute from dsint)
from tt
Run Code Online (Sandbox Code Playgroud)

这是一个sqlfiddle演示


Nic*_*nov 4

如果日期仅在时间部分不同,您可以使用日到秒的间隔。例如:

SQL> select (to_date('25.12.12 15:37:32', 'DD.MM.YY HH24:MI:SS')
  2        - to_date('25.12.12 12:45:45', 'DD.MM.YY HH24:MI:SS')) day(0) to second(0) as Time
  3    from dual
  4  ;

TIME
-------------
+0 02:51:47
Run Code Online (Sandbox Code Playgroud)

但显然情况并非总是如此。因此,您可以编写一个长查询来计算不同的时间部分,但我想我会使用这个简单的函数:

SQL> create or replace function DaysToTime(p_val in number)
  2  return varchar2
  3  is
  4    l_hours    number;
  5    l_minutes  number;
  6    l_seconds  number;
  7  begin
  8    l_Hours := 24 * p_val;
  9    l_minutes := (l_hours - trunc(l_hours)) * 60;
 10    l_seconds := (l_minutes - trunc(l_minutes)) * 60;
 11    return to_char(trunc(l_hours), 'fm09')  ||':'||
 12           to_char(trunc(l_minutes), 'fm09')||':'||
 13           to_char(trunc(l_seconds), 'fm09');
 14  end;
 15  /

Function created
Run Code Online (Sandbox Code Playgroud)

现在的查询是:

SQL> select DaysToTime(to_date('25.12.12 15:37:32', 'DD.MM.YY HH24:MI:SS')
  2        - to_date('25.12.12 12:45:45', 'DD.MM.YY HH24:MI:SS')) as Time
  3    from dual
  4  ;

TIME
----------
02:51:47
Run Code Online (Sandbox Code Playgroud)