大家帮忙想想这个sql怎么写。小弟不胜感激我有这样一个表用来记录电表的故障,
id ammeter_id time  
1 1 2010-1-1
2 1 2010-7-20
3 1 2010-7-21
4 1 2010-7-22
5 2 2010-7-1
6 2 2010-7-2
7 2 2010-7-22如果我向搜索7月22号以前连续发生故障的电表,有人会每天记录有故障的电表
则返回 ammeter_id time last_time
  1 2010-7-22 3 (因为20、21、22 连续三天)
  2 2010-7-22 1 (因为只有22号连续一天)

解决方案 »

  1.   

    查查MIN的用法,用MIN就可以做到。。
      

  2.   

    我想问下楼主,你7月22号以前连续发生故障的电表,为什么 有这笔啊 【2 2010-7-22 1 (因为只有22号连续一天)】7月22号以前连续的时间是:5 2 2010-7-1   和  6 2 2010-7-2我觉得是不是这样的:
    SQL> select ammeter_id , min(time) 开始时间,max(time) 结束时间,count(1) 故障次数
      2  from
      3  (select id, ammeter_id, time ,
      4  row_number()over(partition by ammeter_id order by time) rn
      5  from test )
      6  group by ammeter_id,time-rn
      7  having count(1)>1;AMMETER_ID 开始时间    结束时间      故障次数
    ---------- ----------- ----------- ----------
    1          2010-7-20   2010-7-22            3
    2          2010-7-1    2010-7-2             2SQL> 
      

  3.   

    谢谢兄弟帮忙,是这样的。
    有个程序会每天把有故障的电表录入者个表,如过没录入,说明电表在那天是好的。 所以7月22 只有一天。
    我用这个sql是想统计出最近发生故障的电表,同时说明这个故障发生了几天。
    如果查询的日起2010-8-1,那么返回结果应该为空,因为最大日期8月1号就一条记录没有,说明8月1号电表都是好的。
      

  4.   

    楼主,我理解你意思了,下面是我的测试SQL:数据(跟你提供的一样):
    create table test as 
    with test as(
    select '1' id ,'1' ammeter_id,to_date('2010-1-1','yyyy-mm-dd') time from dual
    union all
    select '2','1',to_date('2010-7-20','yyyy-mm-dd') from dual
    union all
    select '3','1',to_date('2010-7-21','yyyy-mm-dd') from dual
    union all
    select '4','1',to_date('2010-7-22','yyyy-mm-dd') from dual
    union all
    select '5','2',to_date('2010-7-1','yyyy-mm-dd') from dual
    union all
    select '6','2',to_date('2010-7-2','yyyy-mm-dd') from dual
    union all
    select '7','2',to_date('2010-7-22','yyyy-mm-dd') from dual
    )
    select * from test;SQL:
    select ammeter_id ,max(time) 结束时间,count(1) 故障天数
    from  
    (select id, ammeter_id, time ,
    row_number()over(partition by ammeter_id order by time) rn
    from test where time<= to_date('2010-7-22','yyyy-mm-dd')
    )  
    start with time= to_date('2010-7-22','yyyy-mm-dd')
    connect by PRIOR time-1=time AND PRIOR ammeter_id=ammeter_id
    group by ammeter_id,time-rn;结果:
    AMMETER_ID 结束时间      故障天数
    ---------- ----------- ----------
    1          2010-7-22            3
    2          2010-7-22            1
      

  5.   

    上面的条件to_date('2010-7-22','yyyy-mm-dd') 你可以指定查询哪天
      

  6.   

    最后补充一点:
    只根据ammeter_id分组就可以了select ammeter_id ,max(time) 结束时间,count(1) 故障天数
    from  
    (select id, ammeter_id, time 
    from test where time<= to_date('2010-7-22','yyyy-mm-dd')
    )  
    start with time= to_date('2010-7-22','yyyy-mm-dd')
    connect by PRIOR time-1=time AND PRIOR ammeter_id=ammeter_id
    group by ammeter_id;