- 跳轉到2日最後代碼塊爲:
*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
有了這個查詢,我們現在可以測試看看是否有任何ga ps的,由 數着日子在日曆天對
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
的預期數量的另一種方式做,這是剛剛修建從@啓動 日曆@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)
查詢跨度返回所有日期是在日期範圍@啓動差距 - @end 一個TOP 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
)