查询行取决于StartDate和EndDate

时间:2014-03-31 15:02:17

标签: sql tsql sql-server-2012

我想检索给定开始日期和结束日期之间的WeekID

例如, StartDate = 2014-01-20 EndDate = 2014-02-20

所以,结果应该是...... 201404,201405,201406,201407,201408

enter image description here

我尝试像下面那样运行查询,但它返回空白。

DECLARE @StartDate DATETIME
DECLARE @EndDate DATETIME

SET @StartDate = '20140120'
SET @EndDate = '20140220'

SELECT 
    WeekID
FROM
    dbo.DimWeeks
WHERE
    (@StartDate >= FirstDayOfTheWeek 
    AND @EndDate <= LastDayOfTheWeek)

2 个答案:

答案 0 :(得分:0)

查询正常,您没有记录,因为没有FirstDayOfTheWeek <= 20140120LastDayOfTheWeek >= 20140220的行。

也许你想要这个:

WHERE
    ( FirstDayOfTheWeek >= @StartDate
 AND  LastDayOfTheWeek  <= @EndDate)

答案 1 :(得分:0)

我认为这就是你想要的:

where @StartDate <= LastDayOfTheWeek and
      @EndDate >= FirstDayOfTheWeek

当一个区间在另一个区域之前开始而第一个区域在另一个区域开始之后结束时,两个区间重叠。