将后续日期分组到箱子中

时间:2015-03-01 16:16:00

标签: sql sql-server sql-server-2012 group-by lead

假设我有下表:

date         version  
2015-02-01   v1
2015-02-02   v1
2015-02-03   v1
2015-02-04   v1
2015-02-02   v2
2015-02-03   v2
2015-02-08   v1
2015-02-09   v1

我的查询应以这样的方式对日期进行分组:

datefrom      dateto      version
2015-02-01    2015-02-04  v1
2015-02-08    2015-02-09  v1
2015-02-02    2015-02-03  v2

我尝试了

LEAD(date) OVER(PARTITION BY version ORDER BY date)

但它并没有真正得到回报,因为我无法对日期的“垃圾箱”进行分组。 我想将每个后续日期分组到bin上,不允许日期间隔。

1 个答案:

答案 0 :(得分:5)

您可以将行号与datediff比较到固定日期,如果这些变化的差异,则必须至少有一天的差距。所以,像这样:

select
  version,
  min (date) as datefrom,
  max (date) as dateto
from
  (
    select
      version,
      date,
      datediff(day, '20100101', date) 
      - row_number() over (partition by version order by date) as bin
    from
      version
  ) T
group by
  version,
  bin
order by
  version,
  datefrom