在oracle sql中减去两个日期

时间:2014-03-25 12:10:34

标签: sql oracle

我正在计算一份工作的开始和结束时间之间花费的时间。这是我的疑问:

SELECT request_id, user_concurrent_program_name,
DECODE(phase_code,'C','Completed',phase_code) phase_code,
DECODE(status_code,'D', 'Cancelled' ,
'E', 'Error' , 'G', 'Warning',
'H','On Hold' , 'T', 'Terminating',
'M', 'No Manager' , 'X', 'Terminated',
'C', 'Normal', status_code) status_code,
actual_start_date, actual_completion_date, completion_text 
FROM apps.fnd_conc_req_summary_v
WHERE phase_code='C' AND
status_code='C'
ORDER BY 6 DESC

actual_start_dateactual_completion_date的类型为DATE,格式如下:

ACTUAL_START_DATE          ACTUAL_COMPLETION_DATE
3/25/2014 2:00:14 PM       3/25/2014 2:00:18 PM

问题是,我如何减去这两列并获得00:00:04

之类的内容

在某些情况下,作业可以运行两天,我应该得到像2 days and 00:00:02

这样的结果

1 个答案:

答案 0 :(得分:1)

以下方法提取日期组件,然后使用to_char()格式化时间:

select (trunc(ACTUAL_COMPLETION_DATE - ACTUAL_START_DATE) || ' days and ' ||
        to_char(to_date('2000-01-01', 'YYYY-MM-DD') + (ACTUAL_COMPLETION_DATE - ACTUAL_START_DATE),
                'HH24:MI:SS'
               )
       )

在您的主查询中,您只需将其添加到select列表的末尾:

SELECT request_id, user_concurrent_program_name,
       DECODE(phase_code, 'C', 'Completed', phase_code) phase_code,
       DECODE(status_code, 'D', 'Cancelled' , 'E', 'Error' , 'G', 'Warning',
              'H','On Hold' , 'T', 'Terminating', 'M', 'No Manager' , 'X', 'Terminated',
              'C', 'Normal', status_code
              ) as status_code,
       actual_start_date, actual_completion_date, completion_text 
       (trunc(ACTUAL_COMPLETION_DATE - ACTUAL_START_DATE) || ' days and ' ||
        to_char(to_date('2000-01-01', 'YYYY-MM-DD') + (ACTUAL_COMPLETION_DATE - ACTUAL_START_DATE),
                'HH24:MI:SS'
               )
       ) as Diff_DDHHMMSS
FROM apps.fnd_conc_req_summary_v
WHERE phase_code='C' AND
status_code='C'
ORDER BY 6 DESC;