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

时间:2013-05-31 17:14:37

标签: 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中编写代码。

2 个答案:

答案 0 :(得分: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
更新

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

SQLFiddle

答案 1 :(得分:4)

尝试:

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