我正在尝试解决如何在一系列记录中找到连续年份的最大计数的问题。在下面的例子中:
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 中编写代码。
最佳答案
这将产生您想要的结果:
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 已更新以显示最长延伸的开始/结束年份。
关于sql - 查找表中每个 ID 的最大连续年份(Oracle SQL),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16862517/