Find the maximum consecutive years for each ID's in a table(Oracle SQL)

前端 未结 2 571
遥遥无期
遥遥无期 2020-12-16 08:17

I am trying to solve a problem of how to find the maximum count of consecutive years in a series of records. In the following example:

ID  Year
1 1993
1 1994
1 19         


        
相关标签:
2条回答
  • 2020-12-16 08:55

    Try:

    with cte as
    (select t.id, t.year, d.d, row_number() over (partition by t.id, d.d 
                                                  order by t.year) rn
     from (select -1 d from dual union all select 1 d from dual) d
     cross join my_table t 
     where not exists
           (select null
            from my_table o
            where t.id = o.id and t.year = o.year-d.d) )
    select s.id, max(e.year-s.year)+1 year_count
    from cte s
    join cte e on s.id = e.id and s.rn = e.rn and e.d=1
    where s.d=-1
    group by s.id
    

    SQLFiddle here.

    0 讨论(0)
  • 2020-12-16 09:12

    This will produce your desired result:

    select
      id,
      ayear,
      byear,
      yeardiff
    from
    (
      select
        a.id,
        a.year ayear,
        b.year byear,
        (b.year - a.year)+1 yeardiff,
        dense_rank() over (partition by a.id order by (b.year - a.year) desc) rank
      from
        years a
        join years b on a.id = b.id 
            and b.year > a.year
      where
        b.year - a.year = 
          (select count(*)-1
             from years a1
            where a.id = a1.id
                 and a1.year between a.year and b.year)
    )
    where
      rank = 1
    

    EDIT updated to display start/end years of longest stretch.

    SQLFiddle

    0 讨论(0)
提交回复
热议问题