我输出如下
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 )
答案 0 :(得分: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
从那里我认为你得到你想要的确切输出应该是非常简单的。