开发者

calculate difference in date and time using oracle

start_time        end_time     
7/11/2011 21:37   7/11/2011 13:开发者_StackOverflow社区31      
7/20/2011 15:20   7/22/2011 13:37      
9/11/2010 6:00    7/26/2011 16:48      
7/14/2011 20:02   7/26/2011 16:48      
null              4/11/2011 14:07      
null              1/19/2011 13:37      
null              1/19/2011 13:37      
null              1/19/2011 13:37      
null               8/1/2011 13:38   

I need to calculate the difference between the start time and end time , in the format days:hrs:min , only if the start_time <> null.

the desired output will be

start_time        end_time             duration
7/11/2011 21:37   7/11/2011 13:31      0:08:06
7/20/2011 15:20   7/22/2011 13:37      
9/11/2010 6:00    7/26/2011 16:48      
7/14/2011 20:02   7/26/2011 16:48      
null              4/11/2011 14:07      
null              1/19/2011 13:37      
null              1/19/2011 13:37      
null              1/19/2011 13:37      
null               8/1/2011 13:38   


You can use intervals:

SQL> SELECT start_time, end_time,
  2         CASE WHEN diff IS NOT NULL THEN
  3            sgn
  4            || extract(DAY FROM diff) || ':'
  5            || extract(hour FROM diff) || ':'
  6            || extract(minute FROM diff)
  7         END diff
  8    FROM (SELECT start_time, end_time,
  9                 numtodsinterval(abs(end_time - start_time), 'DAY') diff,
 10                  CASE WHEN end_time < start_time THEN '-' END sgn
 11             FROM DATA);

START_TIME  END_TIME    DIFF
----------- ----------- -----------
11/07/2011  11/07/2011  -0:8:6
20/07/2011  22/07/2011  1:22:16
11/09/2010  26/07/2011  318:10:48
14/07/2011  26/07/2011  11:20:46
            11/04/2011  
            19/01/2011  
            19/01/2011  
            19/01/2011  
            01/08/2011  


You can try with this SQL:

    select  start_time, end_time, 
    (CASE WHEN start_time is not null then trunc(start_time-end_time)||':'||
      lpad(trunc(mod((start_time-end_time)*24, 24)),2,'0')||':'||
     lpad(trunc(mod((start_time-end_time)*24*60,60)),2,0) else '' end) duration
     from 
        (select to_date('7/11/2011 21:37','DD/MM/YYYY HH24:MI:SS') start_time,
                to_date('7/11/2011 13:31','DD/MM/YYYY HH24:MI:SS') end_time
          from dual
          union all
          select null start_time,
                to_date('04/08/2011 20:13:43','DD/MM/YYYY HH24:MI:SS') end_time
          from dual
        )

If you need duration in absotule terms, you can put a ABS function.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜