2014-09-26 155 views
0

我試圖過濾一些值,我需要知道它們是否可以在兩個日期之間,但我不能創建一個SQL來執行此操作。如何獲得兩個日期之間的日期?

我有以下日期:May 10 2010

我需要找到這個日期是否可以在兩個日期之間,如果我添加幾年。

例子1:這個日期可以在January 15 2014June 20 2014之間嗎?

是的,因爲May 10 2014是。

例子2:這個日期可以在May 15 2014June 20 2014之間嗎?

不,因爲May 10 2014May 10 2015不在此間隔之間。

例3:這個日期可以在December 15 2013June 20 2014之間嗎?

是的,因爲May 10 2014是。

回答

1

這在SQL Server中有點棘手。我認爲最好的方法是根據時間段的開始將日期規範化爲1月1日。然後,您可以安全地使用datediff()來添加適當的年份值。

事情是這樣的:

select (case when dateadd(year, datediff(year, newdate, newstart), newdate) 
         between newstart and newend 
      then 'Between' else 'NotBetween' 
     end) 
from (select (StartDate - datepart(dayofyear, startDate) + 1) as newstart 
      (EndDate - datepart(dayofyear, StartDate) + 1) as newend, 
      (TheDate - datepart(dayofyear, StartDate) + 1) as newdate 
     from (select cast('2013-12-15' as datetime) as StartDate, 
        cast('2014-06-20' as datetime) as EndDate, 
        cast('2010-05-10' as datetime) as thedate 
      ) dates 
    ) dates; 
+1

請注意,CAST('2010-05-10'AS datetime)'將於10月5日在歐洲舉行。始終使用區域設置獨立的日期文字。即'20100510' – adrianm 2014-09-26 06:26:12

+0

@adrianm。 。 。我將堅持使用ISO標準日期格式,並認爲這是SQL Server中的一個錯誤。不過,我可能在這個意見上是少數。 – 2014-09-26 11:15:34

1

如何以下方法:

  • 如果日期範圍開始日期和結束日期均具有相同的年份,然後檢查是否與該範圍內的每年更換的一年日期落在你的範圍之間;
  • 如果您的日期範圍結束年份比您的日期範圍開始年份多完整一年,則檢查以範圍開始日期的年份替換年份的日期是否落在您的範圍之間或者替換日期範圍結束日期的年份落在您的範圍之間;
  • 如果您的日期範圍結束一年至少2年以上的日期範圍開始的一年,那麼它會一直工作

你可能會雖然陷入困境與2月29日

0

這裏有一個例子

DECLARE @input datetime ='May 10 2010' 

set @input = (select dateadd(year, 4, @input)) 



select * from T 
where @input >= 'January 15 2014' 
       and @input <= 'June 20 2014' 
2

你可以嘗試這樣的事情:

declare @intervals table (StartDate date, EndDate date); 
declare @date date = '2010-05-10'; 

insert into @intervals values 
    ('2014-01-15', '2014-06-20'), 
    ('2014-05-15', '2014-06-20'), 
    ('2013-12-15', '2014-06-20'); 

select case when dateadd(year,year(EndDate)-year(@date),@date) 
       between StartDate and EndDate 
      then 'Yes' 
      else 'No' 
     end, 
     StartDate, 
     EndDate 
    from @intervals; 

輸出

 StartDate EndDate 
---- ---------- ---------- 
Yes 2014-01-15 2014-06-20 
No 2014-05-15 2014-06-20 
Yes 2013-12-15 2014-06-20 
0

一個簡單的方法來做到這一點將檢查使用DateDiff。

DECLARE @input datetime ='May 10 2014' 

select case when DATEDIFF(d,'2014-01-15',@input) >=0 and DATEDIFF(d,@input, '2014-06-20') >= 0 then 'yes' else 'No' end 
相關問題