1

我的输出如下

ID      Date 
Null    2012-10-01
1       2012-10-02
2       2012-10-03
NULL    2012-10-04
3       2012-10-05
NULL    2012-10-06
4       2012-10-07
NULL    2012-10-08
5       2012-10-10
NULL    2012-10-11
NULL    2012-10-12
6       2012-10-13
NULL   2012-10-16

因为它缺少值为 NULL 的日期。我需要将最终输出显示为

2012-10-01 - 2012-10-01 (1 day )
2012-10-04 - 2012-10-04(1 day )
2012-10-06 - 2012-10-06(1 day )
2012-10-08 - 2012-10-08(1 day )
2012-10-11 - 2012-10-12(2 day )
2012-10-14 - 2012-10-14(1 day )
4

1 回答 1

0

您可以使用以下查询生成日期范围:

select
  min(date) as start,
  max(date) as end,
  datediff(max(date), min(date)) + 1 as numDays
from
  (select @curRow := @curRow + 1 AS row_number, id, date
   from Table1 join (SELECT @curRow := 0) r where ID is null) T
group by
  datediff(date, '2012-10-01 00:00:00') - row_number;

该逻辑基于对连续范围进行分组的巧妙技巧。首先,我们对子查询中的行进行过滤和编号。然后,通过将之后的天数与行号进行比较,找到组合在一起2012-10-01的行。如果任何行共享此值,则它们必须是连续的,否则两行之间会出现“跳转”,表达式datediff(date, '2012-10-01 00:00:00') - row_number将不再匹配。

样本输出(DEMO):

START                           END                             NUMDAYS
October, 01 2012 00:00:00+0000  October, 01 2012 00:00:00+0000  1
October, 04 2012 00:00:00+0000  October, 04 2012 00:00:00+0000  1
October, 06 2012 00:00:00+0000  October, 06 2012 00:00:00+0000  1
October, 08 2012 00:00:00+0000  October, 08 2012 00:00:00+0000  1
October, 11 2012 00:00:00+0000  October, 12 2012 00:00:00+0000  2
October, 16 2012 00:00:00+0000  October, 16 2012 00:00:00+0000  1

从那里我认为获得您正在寻找的确切输出应该是微不足道的。

于 2013-03-06T17:46:31.430 回答