3

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

身份证年
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

我的结果集应该看起来像

身份证号码
1 3
2 4

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

4

3 回答 3

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

于 2013-05-31T17:57:07.203 回答
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在这里

于 2013-05-31T17:45:27.373 回答
-2

t1 为 ( select id, year, Lead(year) over(partition by id order by year) as nxt_yr from tree ), t2 as ( select id, year, nxt_yr, nxt_yr - year as diff from t1 ), t3 as ( select id, year, nxt_yr, diff, lag(diff) over(partition by id order by year) as diff_lag, lead(diff) over(partition by id order by year) as diff_lead from t2 ) select id, sum(diff) + 1 from t3 where ((diff = 1) and (diff_lag = 1)) or ((diff = 1) and (diff_lead = 1)) group by id

于 2021-08-15T23:11:47.033 回答