我需要找出两个日期之间的记录,但棘手的部分是获取过去5年之间的记录。例如,我将开始日期设为“12/01”,结束日期为“12/31”所以我需要过去5年“12月01日”和“12月31日”之间的记录。这意味着记录应该在每年的月份和日期之间。不是所有月份。我正在尝试以下但它不起作用:
DECLARE @StartDate DATE = '12/01/2011', @EndDate DATE = '12/01/2016'
DECLARE @StartDay VARCHAR(2) = '01'
,@EndDay VARCHAR(2) = '31'
,@StartMonth VARCHAR(2) = '12'
,@EndMonth VARCHAR(2) = '12'
,@CurrentYear VARCHAR(2) = '2016'
SELECT * FROM [Records]
WHERE [UpdatedDate] BETWEEN @StartDate AND @EndDate
AND (DAY([UpdatedDate]) = CAST(@StartDay AS INT) OR DAY([UpdatedDate]) = CAST(@EndDay AS INT))
AND (MONTH([UpdatedDate]) = CAST(@StartMonth AS INT) OR MONTH([UpdatedDate]) = CAST(@EndMonth AS INT))
AND (YEAR([UpdatedDate]) = CAST((@CurrentYear - 5) AS INT) OR YEAR([UpdatedDate]) = CAST(@CurrentYear AS INT))
答案 0 :(得分:1)
换句话说,在过去的5年中,您只需要12月的记录。 您可以检查DATE字段的月份和年份部分。 这应该是2010年至2015年之间的年份,月份等于12年。
这样的事情:
select id,name,bookyear
from tab1
where year(bookyear) BETWEEN 2010 AND 2015;
and month(bookyear)= 12
希望这有帮助
答案 1 :(得分:0)
select
*
from
Records
where
(year(UpdatedDate) between @CurrentYear and (@CurrentYear + 5))
and (month(UpdatedDate) between @StartMonth and @EndMonth)
and (day(UpdatedDate) between @StartDay and @EndDay)