Oracle SQL计算日期之间的天数、小时数和分钟数

uoifb46i  于 2023-03-22  发布在  Oracle
关注(0)|答案(2)|浏览(160)

我使用此查询来显示代理名称resolved_by和他/她解析的服务计数,此外,我还想显示每个代理解析的所有服务从报告服务creation_Date到解析服务last_resolved_date之间所花费的时间总和,并且我想以天、小时和分钟显示该时间,我该怎么做呢?下面的查询给出了奇怪的结果

select resolved_by,
count(resolved_by) services_resolved,
 
     round(sum((last_resolved_date+0)-(creation_date+0)),0)  || 'Days' ||
    round(sum(((last_resolved_date+0)-(creation_date+0))*24),0) || 'Hours' ||
    round(sum(((last_resolved_date+0)-(creation_date+0))*24*60),0) || 'Minutes' effort
 from svc_service_requests

where status_type_cd = 'ORA_SVC_RESOLVED'

group by resolved_by

例如:14 Days 327 Hours 19598 Minutes

dohp0rv5

dohp0rv51#

下面是一个通用函数,它接受日期或时间戳,并返回两者的差值

CREATE FUNCTION datediff (p_from timestamp, p_to timestamp)
return varchar2 is
  v_from     TIMESTAMP := LEAST(p_from, p_to);
  v_to       TIMESTAMP := GREATEST(p_from, p_to);
  l_years    PLS_INTEGER;
  l_from     TIMESTAMP;
  l_interval interval day(3) to second(6);
begin
  l_years    := TRUNC(MONTHS_BETWEEN(v_to, v_from)/12);
  l_from     := CAST(TRUNC(ADD_MONTHS(v_from, l_years * 12), 'MI') AS TIMESTAMP)
                  + NUMTODSINTERVAL( EXTRACT(SECOND FROM v_from), 'SECOND' );
  l_interval := (v_to - l_from) DAY(3) TO SECOND(6);
  return l_years || ' Years '
    || extract (day from l_interval) || ' Days '
    || extract (hour from l_interval) || ' Hours '
    || extract (minute from l_interval) || ' Minutes '
    || extract (second from l_interval) || ' Seconds';
end datediff;
/

SELECT 
datediff( TO_DATE('2022-04-03 10:11:13','YYYY-MM-DD HH24:MI:SS'), 
TO_DATE('2001-05-10 17:48:09','YYYY-MM-DD HH24:MI:SS')) as  diff FROM DUAL

DIFF
20 Years 327 Days 16 Hours 23 Minutes 4 Seconds
7ajki6be

7ajki6be2#

使用MOD获取小时/分钟和TRUNC(或FLOOR):

select resolved_by,
       count(resolved_by) AS services_resolved,
       TRUNC(sum(last_resolved_date - creation_date)) || 'Days'
       || TRUNC(MOD(sum(last_resolved_date - creation_date)*24, 24)) || 'Hours'
       || TRUNC(MOD(sum(last_resolved_date - creation_date)*24*60, 60)) || 'Minutes'
         AS effort
from   svc_service_requests
where status_type_cd = 'ORA_SVC_RESOLVED'
group by resolved_by

如果列是TIMESTAMP s,则可以使用CAST(last_resolved_date AS DATE)CAST(creation_date AS DATE)

相关问题