查找表中每个ID的最大连续年数(Oracle SQL)

avg*_*877 3 sql oracle

我试图解决如何在一系列记录中找到连续年份的最大数量的问题.在以下示例中:

ID  Year
1 1993
1 1994
1 1995
1 1995
1 2001
1 2002
2 1993
2 1995
2 1996
2 1996
2 1998
2 1999
2 2000
2 2001
2 2001

我的结果集应该是这样的

id   count
1      3
2      4

我必须在oracle SQL中编写代码.

Joe*_*Joe 5

这将产生您想要的结果:

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
Run Code Online (Sandbox Code Playgroud)

编辑更新以显示最长拉伸的开始/结束年份.

SQLFiddle