现在有一个错误统计表,如tablename(faultid,faulttype,context,starttime,endtime),需要根据错误类型统计出每一种错误的故障时长,如:
faultid   faulttype   context      starttime              endtime
00012     网络          网络中断       2007-02-12 10:00:00    2007-02-13 10:00:00
00014     硬件          网卡检测失败   2008-12-12 10:00:00    
00015     硬件          显示器链接失败 2009-02-12 17:56:02    2009-02-13 12:23:11
00013     网络          网络中断       2008-11-12 09:12:14    2009-01-13 02:23:10
00011     网络          网络中断       2008-05-12 10:25:00    
00112     应用程序      程序异常       2008-11-12 13:00:00    2008-12-13 10:20:00
05012     网络          网络中断       2008-10-12 08:00:22    2009-02-13 10:00:00
03012     网络          网络中断       2008-11-22 10:45:00    
现在需要计算时间2008-05-12 10:00:00与2009-02-15 12:00:00之间的各故障类型的发生总时间,即如"网络"类型故障总时间,则计算id号为:00013,00011,05012,03012的故障时间总和,没有结束时间的以给定时间为结束时间,如03012的网络故障则计算时间2008-11-22 10:45:00到2009-02-15 12:00:00之间的时间。
基本想法是先选出给定时间范围内的所有记录,然后分类,再对每一类型中的每一条记录进行时间计算,最后相加。不知道用最少的sql语句怎么实现?求高人指点指点!

解决方案 »

  1.   

    各故障的总时间:
    select faultid,sum(to_date(endtime,'yyyy-mm-dd')-to_date(starttime,'yyyy-mm-dd')) total
    from
    (select faultid,faulttype,context,starttime,decode(endtime,'','2009-02-15 12:00:00',endtime) endtime
    from tb)
    where to_char(starttime,'yyyy-mm-dd HH24:mm:ss')>='2008-05-12 10:00:00' 
    and to_char(endtime,'yyyy-mm-dd HH24:mm:ss')<='2009-02-15 12:00:00'
    group by faultid;
      

  2.   

    纠正一下,按类型分则是这样的
    select faulttype,sum(to_date(endtime,'yyyy-mm-dd')-to_date(starttime,'yyyy-mm-dd')) total 
    from 
    (select faultid,faulttype,context,starttime,decode(endtime,'','2009-02-15 12:00:00',endtime) endtime 
    from tb) 
    where to_char(starttime,'yyyy-mm-dd HH24:mm:ss')>='2008-05-12 10:00:00' 
    and to_char(endtime,'yyyy-mm-dd HH24:mm:ss') <='2009-02-15 12:00:00' 
    group by faulttype; 
      

  3.   

    如果条件是starttime和endtime都在给定的时间内的select faulttype, sum(endtime - starttime) * 24 * 60 ttltime
      from (select faulttype,
                   starttime,
                   nvl(endtime,
                       to_date('2009-02-15 12:00:00', 'yyyy-mm-dd hh24:mi:ss')) endtime
              from tablename)
     where starttime >= to_date('2008-05-12 10:00:00', 'yyyy-mm-dd hh24:mi:ss')
       and starttime <= to_date('2009-02-15 12:00:00', 'yyyy-mm-dd hh24:mi:ss')
       and endtime >= to_date('2008-05-12 10:00:00', 'yyyy-mm-dd hh24:mi:ss')
       and endtime <= to_date('2009-02-15 12:00:00', 'yyyy-mm-dd hh24:mi:ss')
     group by faulttype如果条件是starttime和endtime只要有一个在给定的时间内的select faulttype, sum(endtime - starttime) * 24 * 60 ttltime
      from (select faulttype,
                   starttime,
                   nvl(endtime,
                       to_date('2009-02-15 12:00:00', 'yyyy-mm-dd hh24:mi:ss')) endtime
              from tablename)
     where starttime <= to_date('2009-02-15 12:00:00', 'yyyy-mm-dd hh24:mi:ss')
       and endtime >= to_date('2008-05-12 10:00:00', 'yyyy-mm-dd hh24:mi:ss')
     group by faulttype我算出的是分钟数