计算最大序列行

时间:2015-12-01 13:12:35

标签: sql oracle oracle11g

我有一个包含日期信息的表格(例如:201501,201502,201510等)。行是varchar但是参考yyymm格式的日期。

例如;


dates
---
201501
201502
201503
201505
201506
201507
201508
201509
201510
201512
201601
201602

有序列月,但缺少'201504'和'201511'。

我想计算rownum直到每个丢失的日期。例如:直到'201504'有3排,在'201504'之后,直到下一个缺失日期('201511')有6排。最后,2排。

<小时/> 我想要最大序列。对于这个例子,输出是6.感谢您的帮助。

2 个答案:

答案 0 :(得分:1)

您可以使用月份计数中的行数差异来为序列分配组ID。因此,以下标识了这样的序列:

select min(d), max(d), count(*)
from (select t.*,
             (to_number(substr(d, 1, 4)) * 12 + to_number(substr(d, 5, 2)) -
              row_number() over (order by d)
             ) as grp
      from t
     ) t
group by grp;

您可以获得最大长度:

with cte as (
      select min(d), max(d), count(*) as len
      from (select t.*,
                   (to_number(substr(d, 1, 4)) * 12 + to_number(substr(d, 5, 2)) - 
                    row_number() over (order by d)
                   ) as grp
            from t
           ) t
      group by grp
     )
select max(len)
from cte;

答案 1 :(得分:1)

SQL Fiddle

Oracle 11g R2架构设置

SELECT MAX( diff ) AS result
FROM (
  SELECT CASE WHEN end_grp IS NOT NULL THEN 1
              ELSE LEAD( end_grp ) IGNORE NULLS OVER ( ORDER BY DATES ) - dates + 1 END as diff
  FROM (
    SELECT DATES,
           CASE next_date WHEN dates+1 THEN NULL ELSE dates END AS end_grp
    FROM (
      SELECT DATES,
             LEAD( DATES ) OVER ( ORDER BY DATES ) AS next_date
      FROM   TABLE_NAME
    )
  )
)

查询1

| RESULT |
|--------|
|      6 |

<强> Results

{{1}}