- 跳转到倒数第二个代码块:
*I want to be able to tell that
between 1/10/11 and 1/13/11 there is
a gap so the start and end date is*
不可能。
- 跳转到最后一个代码块:
*I want to return only
the datespans up to the first gap
encountered.*
首先,这里有一个虚拟表来讨论
create table spans (date1 datetime, date2 datetime);
insert into spans select '20110101', '20110110';
insert into spans select '20110113', '20110115';
insert into spans select '20110120', '20110130';
这是一个查询,将单独列出日历中的所有日期
declare @startdate datetime, @enddate datetime
select @startdate = '20110107', @enddate = '20110114'
select distinct a.date1+v.number
from spans A
inner join master..spt_values v
on v.type='P' and v.number between 0 and datediff(d, a.date1, a.date2)
-- we don't care about spans that don't intersect with our range
where A.date1 <= @enddate
and @startdate <= A.date2
有了这个查询,我们现在可以通过计算日历中的天数与预期天数来测试是否有任何差距
declare @startdate datetime, @enddate datetime
select @startdate = '20110107', @enddate = '20110114'
select case when count(distinct a.date1+v.number)
= datediff(d,@startdate, @enddate) + 1
then 'No gaps' else 'Gap' end
from spans A
inner join master..spt_values v
on v.type='P' and v.number between 0 and datediff(d, a.date1, a.date2)
-- we don't care about spans that don't intersect with our range
where A.date1 <= @enddate
and @startdate <= A.date2
-- count only those dates within our range
and a.date1 + v.number between @startdate and @enddate
另一种方法是预先构建从@start 到@end 的日历,并查看该日期是否存在跨度
declare @startdate datetime, @enddate datetime
select @startdate = '20110107', @enddate = '20110114'
-- startdate+v.number is a day on the calendar
select @startdate + v.number
from master..spt_values v
where v.type='P' and v.number between 0
and datediff(d, @startdate, @enddate)
-- run the part above this line alone to see the calendar
-- the condition checks for dates that are not in any span (gap)
and not exists (
select *
from spans
where @startdate + v.number between date1 and date2)
查询返回日期范围内所有间隔的日期 @start - @endTOP 1
可以添加一个来查看是否有间隔
要返回间隙之前的所有记录,请将查询用作更大查询中的派生表
declare @startdate datetime, @enddate datetime
select @startdate = '20110107', @enddate = '20110114'
select *
from spans
where date1 <= @enddate and @startdate <= date2 -- overlaps
and date2 < ( -- before the gap
select top 1 @startdate + v.number
from master..spt_values v
where v.type='P' and v.number between 0
and datediff(d, @startdate, @enddate)
and not exists (
select *
from spans
where @startdate + v.number between date1 and date2)
order by 1 ASC
)