确定SQL Server中的连续日期计数

时间:2013-07-15 16:54:12

标签: sql-server

我有一些看起来像这样的数据:

id     date
--------------------------------
123    2013-04-08 00:00:00.000
123    2013-04-07 00:00:00.000
123    2013-04-06 00:00:00.000
123    2013-04-04 00:00:00.000
123    2013-04-03 00:00:00.000

我需要返回给定ID的最近连续日期条纹的计数,在这种情况下,对于标识3,它将是123。我不知道这是否可以在SQL中完成。有什么建议吗?

1 个答案:

答案 0 :(得分:3)

这样做的方法是减去一系列数字并取得差异。这是一系列日期的常量。下面是一个获取id的所有序列长度的示例:

select id, grp, count(*) as NumInSequence, min(date), max(date)
from (select t.*,
             (date - row_number() over (partition by id order by date)) as grp
      from data t
     ) t
group by id, grp

要获得最长的,我会再次使用row_number()

select t.*
from (select id, grp, count(*) as NumInSequence,
             min(date) as mindate, max(date) as maxdate,
             row_number() over (partition by id order by count(*) desc) as seqnum
      from (select t.*,
                   (date - row_number() over (partition by id order by date)) as grp
            from data t
           ) t
      group by id, grp
     ) t
where seqnum = 1