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

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

最佳答案

这将产生您想要的结果:

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 已更新以显示最长延伸的开始/结束年份。

SQLFiddle

关于sql - 查找表中每个 ID 的最大连续年份(Oracle SQL),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16862517/

相关文章:

sql - WHERE 语句在左外连接中的位置

sql - 选择不同列上具有不同值的行

java - 静态列表 MINUS select 语句

oracle - 确定 PL/SQL 过程的调用层次结构

MySQL ORDER BY 聚合列返回不正确的结果

sql - CodeIgniter - 继续出现 SQL 错误?

oracle - 在 Oracle SQL Developer 连接窗口中选择表时如何避免默认获取表定义

sql - Hibernate 空字符串用于 PostgreSQL 8.3 和 Oracle 11g 的相等限制

sql - Oracle select 中使用窗口函数的运行总计(累积列)有什么问题?

java - Oracle PL/SQL 和 Java 依赖项